logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

handlers.py (59412B)


  1. # Copyright 2001-2016 by Vinay Sajip. All Rights Reserved.
  2. #
  3. # Permission to use, copy, modify, and distribute this software and its
  4. # documentation for any purpose and without fee is hereby granted,
  5. # provided that the above copyright notice appear in all copies and that
  6. # both that copyright notice and this permission notice appear in
  7. # supporting documentation, and that the name of Vinay Sajip
  8. # not be used in advertising or publicity pertaining to distribution
  9. # of the software without specific, written prior permission.
  10. # VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
  11. # ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
  12. # VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
  13. # ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
  14. # IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  15. # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. """
  17. Additional handlers for the logging package for Python. The core package is
  18. based on PEP 282 and comments thereto in comp.lang.python.
  19. Copyright (C) 2001-2016 Vinay Sajip. All Rights Reserved.
  20. To use, simply 'import logging.handlers' and log away!
  21. """
  22. import io, logging, socket, os, pickle, struct, time, re
  23. from stat import ST_DEV, ST_INO, ST_MTIME
  24. import queue
  25. import threading
  26. import copy
  27. #
  28. # Some constants...
  29. #
  30. DEFAULT_TCP_LOGGING_PORT = 9020
  31. DEFAULT_UDP_LOGGING_PORT = 9021
  32. DEFAULT_HTTP_LOGGING_PORT = 9022
  33. DEFAULT_SOAP_LOGGING_PORT = 9023
  34. SYSLOG_UDP_PORT = 514
  35. SYSLOG_TCP_PORT = 514
  36. _MIDNIGHT = 24 * 60 * 60 # number of seconds in a day
  37. class BaseRotatingHandler(logging.FileHandler):
  38. """
  39. Base class for handlers that rotate log files at a certain point.
  40. Not meant to be instantiated directly. Instead, use RotatingFileHandler
  41. or TimedRotatingFileHandler.
  42. """
  43. namer = None
  44. rotator = None
  45. def __init__(self, filename, mode, encoding=None, delay=False, errors=None):
  46. """
  47. Use the specified filename for streamed logging
  48. """
  49. logging.FileHandler.__init__(self, filename, mode=mode,
  50. encoding=encoding, delay=delay,
  51. errors=errors)
  52. self.mode = mode
  53. self.encoding = encoding
  54. self.errors = errors
  55. def emit(self, record):
  56. """
  57. Emit a record.
  58. Output the record to the file, catering for rollover as described
  59. in doRollover().
  60. """
  61. try:
  62. if self.shouldRollover(record):
  63. self.doRollover()
  64. logging.FileHandler.emit(self, record)
  65. except Exception:
  66. self.handleError(record)
  67. def rotation_filename(self, default_name):
  68. """
  69. Modify the filename of a log file when rotating.
  70. This is provided so that a custom filename can be provided.
  71. The default implementation calls the 'namer' attribute of the
  72. handler, if it's callable, passing the default name to
  73. it. If the attribute isn't callable (the default is None), the name
  74. is returned unchanged.
  75. :param default_name: The default name for the log file.
  76. """
  77. if not callable(self.namer):
  78. result = default_name
  79. else:
  80. result = self.namer(default_name)
  81. return result
  82. def rotate(self, source, dest):
  83. """
  84. When rotating, rotate the current log.
  85. The default implementation calls the 'rotator' attribute of the
  86. handler, if it's callable, passing the source and dest arguments to
  87. it. If the attribute isn't callable (the default is None), the source
  88. is simply renamed to the destination.
  89. :param source: The source filename. This is normally the base
  90. filename, e.g. 'test.log'
  91. :param dest: The destination filename. This is normally
  92. what the source is rotated to, e.g. 'test.log.1'.
  93. """
  94. if not callable(self.rotator):
  95. # Issue 18940: A file may not have been created if delay is True.
  96. if os.path.exists(source):
  97. os.rename(source, dest)
  98. else:
  99. self.rotator(source, dest)
  100. class RotatingFileHandler(BaseRotatingHandler):
  101. """
  102. Handler for logging to a set of files, which switches from one file
  103. to the next when the current file reaches a certain size.
  104. """
  105. def __init__(self, filename, mode='a', maxBytes=0, backupCount=0,
  106. encoding=None, delay=False, errors=None):
  107. """
  108. Open the specified file and use it as the stream for logging.
  109. By default, the file grows indefinitely. You can specify particular
  110. values of maxBytes and backupCount to allow the file to rollover at
  111. a predetermined size.
  112. Rollover occurs whenever the current log file is nearly maxBytes in
  113. length. If backupCount is >= 1, the system will successively create
  114. new files with the same pathname as the base file, but with extensions
  115. ".1", ".2" etc. appended to it. For example, with a backupCount of 5
  116. and a base file name of "app.log", you would get "app.log",
  117. "app.log.1", "app.log.2", ... through to "app.log.5". The file being
  118. written to is always "app.log" - when it gets filled up, it is closed
  119. and renamed to "app.log.1", and if files "app.log.1", "app.log.2" etc.
  120. exist, then they are renamed to "app.log.2", "app.log.3" etc.
  121. respectively.
  122. If maxBytes is zero, rollover never occurs.
  123. """
  124. # If rotation/rollover is wanted, it doesn't make sense to use another
  125. # mode. If for example 'w' were specified, then if there were multiple
  126. # runs of the calling application, the logs from previous runs would be
  127. # lost if the 'w' is respected, because the log file would be truncated
  128. # on each run.
  129. if maxBytes > 0:
  130. mode = 'a'
  131. if "b" not in mode:
  132. encoding = io.text_encoding(encoding)
  133. BaseRotatingHandler.__init__(self, filename, mode, encoding=encoding,
  134. delay=delay, errors=errors)
  135. self.maxBytes = maxBytes
  136. self.backupCount = backupCount
  137. def doRollover(self):
  138. """
  139. Do a rollover, as described in __init__().
  140. """
  141. if self.stream:
  142. self.stream.close()
  143. self.stream = None
  144. if self.backupCount > 0:
  145. for i in range(self.backupCount - 1, 0, -1):
  146. sfn = self.rotation_filename("%s.%d" % (self.baseFilename, i))
  147. dfn = self.rotation_filename("%s.%d" % (self.baseFilename,
  148. i + 1))
  149. if os.path.exists(sfn):
  150. if os.path.exists(dfn):
  151. os.remove(dfn)
  152. os.rename(sfn, dfn)
  153. dfn = self.rotation_filename(self.baseFilename + ".1")
  154. if os.path.exists(dfn):
  155. os.remove(dfn)
  156. self.rotate(self.baseFilename, dfn)
  157. if not self.delay:
  158. self.stream = self._open()
  159. def shouldRollover(self, record):
  160. """
  161. Determine if rollover should occur.
  162. Basically, see if the supplied record would cause the file to exceed
  163. the size limit we have.
  164. """
  165. if self.stream is None: # delay was set...
  166. self.stream = self._open()
  167. if self.maxBytes > 0: # are we rolling over?
  168. msg = "%s\n" % self.format(record)
  169. self.stream.seek(0, 2) #due to non-posix-compliant Windows feature
  170. if self.stream.tell() + len(msg) >= self.maxBytes:
  171. return 1
  172. return 0
  173. class TimedRotatingFileHandler(BaseRotatingHandler):
  174. """
  175. Handler for logging to a file, rotating the log file at certain timed
  176. intervals.
  177. If backupCount is > 0, when rollover is done, no more than backupCount
  178. files are kept - the oldest ones are deleted.
  179. """
  180. def __init__(self, filename, when='h', interval=1, backupCount=0,
  181. encoding=None, delay=False, utc=False, atTime=None,
  182. errors=None):
  183. encoding = io.text_encoding(encoding)
  184. BaseRotatingHandler.__init__(self, filename, 'a', encoding=encoding,
  185. delay=delay, errors=errors)
  186. self.when = when.upper()
  187. self.backupCount = backupCount
  188. self.utc = utc
  189. self.atTime = atTime
  190. # Calculate the real rollover interval, which is just the number of
  191. # seconds between rollovers. Also set the filename suffix used when
  192. # a rollover occurs. Current 'when' events supported:
  193. # S - Seconds
  194. # M - Minutes
  195. # H - Hours
  196. # D - Days
  197. # midnight - roll over at midnight
  198. # W{0-6} - roll over on a certain day; 0 - Monday
  199. #
  200. # Case of the 'when' specifier is not important; lower or upper case
  201. # will work.
  202. if self.when == 'S':
  203. self.interval = 1 # one second
  204. self.suffix = "%Y-%m-%d_%H-%M-%S"
  205. self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}(\.\w+)?$"
  206. elif self.when == 'M':
  207. self.interval = 60 # one minute
  208. self.suffix = "%Y-%m-%d_%H-%M"
  209. self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}(\.\w+)?$"
  210. elif self.when == 'H':
  211. self.interval = 60 * 60 # one hour
  212. self.suffix = "%Y-%m-%d_%H"
  213. self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}(\.\w+)?$"
  214. elif self.when == 'D' or self.when == 'MIDNIGHT':
  215. self.interval = 60 * 60 * 24 # one day
  216. self.suffix = "%Y-%m-%d"
  217. self.extMatch = r"^\d{4}-\d{2}-\d{2}(\.\w+)?$"
  218. elif self.when.startswith('W'):
  219. self.interval = 60 * 60 * 24 * 7 # one week
  220. if len(self.when) != 2:
  221. raise ValueError("You must specify a day for weekly rollover from 0 to 6 (0 is Monday): %s" % self.when)
  222. if self.when[1] < '0' or self.when[1] > '6':
  223. raise ValueError("Invalid day specified for weekly rollover: %s" % self.when)
  224. self.dayOfWeek = int(self.when[1])
  225. self.suffix = "%Y-%m-%d"
  226. self.extMatch = r"^\d{4}-\d{2}-\d{2}(\.\w+)?$"
  227. else:
  228. raise ValueError("Invalid rollover interval specified: %s" % self.when)
  229. self.extMatch = re.compile(self.extMatch, re.ASCII)
  230. self.interval = self.interval * interval # multiply by units requested
  231. # The following line added because the filename passed in could be a
  232. # path object (see Issue #27493), but self.baseFilename will be a string
  233. filename = self.baseFilename
  234. if os.path.exists(filename):
  235. t = os.stat(filename)[ST_MTIME]
  236. else:
  237. t = int(time.time())
  238. self.rolloverAt = self.computeRollover(t)
  239. def computeRollover(self, currentTime):
  240. """
  241. Work out the rollover time based on the specified time.
  242. """
  243. result = currentTime + self.interval
  244. # If we are rolling over at midnight or weekly, then the interval is already known.
  245. # What we need to figure out is WHEN the next interval is. In other words,
  246. # if you are rolling over at midnight, then your base interval is 1 day,
  247. # but you want to start that one day clock at midnight, not now. So, we
  248. # have to fudge the rolloverAt value in order to trigger the first rollover
  249. # at the right time. After that, the regular interval will take care of
  250. # the rest. Note that this code doesn't care about leap seconds. :)
  251. if self.when == 'MIDNIGHT' or self.when.startswith('W'):
  252. # This could be done with less code, but I wanted it to be clear
  253. if self.utc:
  254. t = time.gmtime(currentTime)
  255. else:
  256. t = time.localtime(currentTime)
  257. currentHour = t[3]
  258. currentMinute = t[4]
  259. currentSecond = t[5]
  260. currentDay = t[6]
  261. # r is the number of seconds left between now and the next rotation
  262. if self.atTime is None:
  263. rotate_ts = _MIDNIGHT
  264. else:
  265. rotate_ts = ((self.atTime.hour * 60 + self.atTime.minute)*60 +
  266. self.atTime.second)
  267. r = rotate_ts - ((currentHour * 60 + currentMinute) * 60 +
  268. currentSecond)
  269. if r < 0:
  270. # Rotate time is before the current time (for example when
  271. # self.rotateAt is 13:45 and it now 14:15), rotation is
  272. # tomorrow.
  273. r += _MIDNIGHT
  274. currentDay = (currentDay + 1) % 7
  275. result = currentTime + r
  276. # If we are rolling over on a certain day, add in the number of days until
  277. # the next rollover, but offset by 1 since we just calculated the time
  278. # until the next day starts. There are three cases:
  279. # Case 1) The day to rollover is today; in this case, do nothing
  280. # Case 2) The day to rollover is further in the interval (i.e., today is
  281. # day 2 (Wednesday) and rollover is on day 6 (Sunday). Days to
  282. # next rollover is simply 6 - 2 - 1, or 3.
  283. # Case 3) The day to rollover is behind us in the interval (i.e., today
  284. # is day 5 (Saturday) and rollover is on day 3 (Thursday).
  285. # Days to rollover is 6 - 5 + 3, or 4. In this case, it's the
  286. # number of days left in the current week (1) plus the number
  287. # of days in the next week until the rollover day (3).
  288. # The calculations described in 2) and 3) above need to have a day added.
  289. # This is because the above time calculation takes us to midnight on this
  290. # day, i.e. the start of the next day.
  291. if self.when.startswith('W'):
  292. day = currentDay # 0 is Monday
  293. if day != self.dayOfWeek:
  294. if day < self.dayOfWeek:
  295. daysToWait = self.dayOfWeek - day
  296. else:
  297. daysToWait = 6 - day + self.dayOfWeek + 1
  298. newRolloverAt = result + (daysToWait * (60 * 60 * 24))
  299. if not self.utc:
  300. dstNow = t[-1]
  301. dstAtRollover = time.localtime(newRolloverAt)[-1]
  302. if dstNow != dstAtRollover:
  303. if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour
  304. addend = -3600
  305. else: # DST bows out before next rollover, so we need to add an hour
  306. addend = 3600
  307. newRolloverAt += addend
  308. result = newRolloverAt
  309. return result
  310. def shouldRollover(self, record):
  311. """
  312. Determine if rollover should occur.
  313. record is not used, as we are just comparing times, but it is needed so
  314. the method signatures are the same
  315. """
  316. t = int(time.time())
  317. if t >= self.rolloverAt:
  318. return 1
  319. return 0
  320. def getFilesToDelete(self):
  321. """
  322. Determine the files to delete when rolling over.
  323. More specific than the earlier method, which just used glob.glob().
  324. """
  325. dirName, baseName = os.path.split(self.baseFilename)
  326. fileNames = os.listdir(dirName)
  327. result = []
  328. # See bpo-44753: Don't use the extension when computing the prefix.
  329. prefix = os.path.splitext(baseName)[0] + "."
  330. plen = len(prefix)
  331. for fileName in fileNames:
  332. if fileName[:plen] == prefix:
  333. suffix = fileName[plen:]
  334. if self.extMatch.match(suffix):
  335. result.append(os.path.join(dirName, fileName))
  336. if len(result) < self.backupCount:
  337. result = []
  338. else:
  339. result.sort()
  340. result = result[:len(result) - self.backupCount]
  341. return result
  342. def doRollover(self):
  343. """
  344. do a rollover; in this case, a date/time stamp is appended to the filename
  345. when the rollover happens. However, you want the file to be named for the
  346. start of the interval, not the current time. If there is a backup count,
  347. then we have to get a list of matching filenames, sort them and remove
  348. the one with the oldest suffix.
  349. """
  350. if self.stream:
  351. self.stream.close()
  352. self.stream = None
  353. # get the time that this sequence started at and make it a TimeTuple
  354. currentTime = int(time.time())
  355. dstNow = time.localtime(currentTime)[-1]
  356. t = self.rolloverAt - self.interval
  357. if self.utc:
  358. timeTuple = time.gmtime(t)
  359. else:
  360. timeTuple = time.localtime(t)
  361. dstThen = timeTuple[-1]
  362. if dstNow != dstThen:
  363. if dstNow:
  364. addend = 3600
  365. else:
  366. addend = -3600
  367. timeTuple = time.localtime(t + addend)
  368. dfn = self.rotation_filename(self.baseFilename + "." +
  369. time.strftime(self.suffix, timeTuple))
  370. if os.path.exists(dfn):
  371. os.remove(dfn)
  372. self.rotate(self.baseFilename, dfn)
  373. if self.backupCount > 0:
  374. for s in self.getFilesToDelete():
  375. os.remove(s)
  376. if not self.delay:
  377. self.stream = self._open()
  378. newRolloverAt = self.computeRollover(currentTime)
  379. while newRolloverAt <= currentTime:
  380. newRolloverAt = newRolloverAt + self.interval
  381. #If DST changes and midnight or weekly rollover, adjust for this.
  382. if (self.when == 'MIDNIGHT' or self.when.startswith('W')) and not self.utc:
  383. dstAtRollover = time.localtime(newRolloverAt)[-1]
  384. if dstNow != dstAtRollover:
  385. if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour
  386. addend = -3600
  387. else: # DST bows out before next rollover, so we need to add an hour
  388. addend = 3600
  389. newRolloverAt += addend
  390. self.rolloverAt = newRolloverAt
  391. class WatchedFileHandler(logging.FileHandler):
  392. """
  393. A handler for logging to a file, which watches the file
  394. to see if it has changed while in use. This can happen because of
  395. usage of programs such as newsyslog and logrotate which perform
  396. log file rotation. This handler, intended for use under Unix,
  397. watches the file to see if it has changed since the last emit.
  398. (A file has changed if its device or inode have changed.)
  399. If it has changed, the old file stream is closed, and the file
  400. opened to get a new stream.
  401. This handler is not appropriate for use under Windows, because
  402. under Windows open files cannot be moved or renamed - logging
  403. opens the files with exclusive locks - and so there is no need
  404. for such a handler. Furthermore, ST_INO is not supported under
  405. Windows; stat always returns zero for this value.
  406. This handler is based on a suggestion and patch by Chad J.
  407. Schroeder.
  408. """
  409. def __init__(self, filename, mode='a', encoding=None, delay=False,
  410. errors=None):
  411. if "b" not in mode:
  412. encoding = io.text_encoding(encoding)
  413. logging.FileHandler.__init__(self, filename, mode=mode,
  414. encoding=encoding, delay=delay,
  415. errors=errors)
  416. self.dev, self.ino = -1, -1
  417. self._statstream()
  418. def _statstream(self):
  419. if self.stream:
  420. sres = os.fstat(self.stream.fileno())
  421. self.dev, self.ino = sres[ST_DEV], sres[ST_INO]
  422. def reopenIfNeeded(self):
  423. """
  424. Reopen log file if needed.
  425. Checks if the underlying file has changed, and if it
  426. has, close the old stream and reopen the file to get the
  427. current stream.
  428. """
  429. # Reduce the chance of race conditions by stat'ing by path only
  430. # once and then fstat'ing our new fd if we opened a new log stream.
  431. # See issue #14632: Thanks to John Mulligan for the problem report
  432. # and patch.
  433. try:
  434. # stat the file by path, checking for existence
  435. sres = os.stat(self.baseFilename)
  436. except FileNotFoundError:
  437. sres = None
  438. # compare file system stat with that of our stream file handle
  439. if not sres or sres[ST_DEV] != self.dev or sres[ST_INO] != self.ino:
  440. if self.stream is not None:
  441. # we have an open file handle, clean it up
  442. self.stream.flush()
  443. self.stream.close()
  444. self.stream = None # See Issue #21742: _open () might fail.
  445. # open a new file handle and get new stat info from that fd
  446. self.stream = self._open()
  447. self._statstream()
  448. def emit(self, record):
  449. """
  450. Emit a record.
  451. If underlying file has changed, reopen the file before emitting the
  452. record to it.
  453. """
  454. self.reopenIfNeeded()
  455. logging.FileHandler.emit(self, record)
  456. class SocketHandler(logging.Handler):
  457. """
  458. A handler class which writes logging records, in pickle format, to
  459. a streaming socket. The socket is kept open across logging calls.
  460. If the peer resets it, an attempt is made to reconnect on the next call.
  461. The pickle which is sent is that of the LogRecord's attribute dictionary
  462. (__dict__), so that the receiver does not need to have the logging module
  463. installed in order to process the logging event.
  464. To unpickle the record at the receiving end into a LogRecord, use the
  465. makeLogRecord function.
  466. """
  467. def __init__(self, host, port):
  468. """
  469. Initializes the handler with a specific host address and port.
  470. When the attribute *closeOnError* is set to True - if a socket error
  471. occurs, the socket is silently closed and then reopened on the next
  472. logging call.
  473. """
  474. logging.Handler.__init__(self)
  475. self.host = host
  476. self.port = port
  477. if port is None:
  478. self.address = host
  479. else:
  480. self.address = (host, port)
  481. self.sock = None
  482. self.closeOnError = False
  483. self.retryTime = None
  484. #
  485. # Exponential backoff parameters.
  486. #
  487. self.retryStart = 1.0
  488. self.retryMax = 30.0
  489. self.retryFactor = 2.0
  490. def makeSocket(self, timeout=1):
  491. """
  492. A factory method which allows subclasses to define the precise
  493. type of socket they want.
  494. """
  495. if self.port is not None:
  496. result = socket.create_connection(self.address, timeout=timeout)
  497. else:
  498. result = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  499. result.settimeout(timeout)
  500. try:
  501. result.connect(self.address)
  502. except OSError:
  503. result.close() # Issue 19182
  504. raise
  505. return result
  506. def createSocket(self):
  507. """
  508. Try to create a socket, using an exponential backoff with
  509. a max retry time. Thanks to Robert Olson for the original patch
  510. (SF #815911) which has been slightly refactored.
  511. """
  512. now = time.time()
  513. # Either retryTime is None, in which case this
  514. # is the first time back after a disconnect, or
  515. # we've waited long enough.
  516. if self.retryTime is None:
  517. attempt = True
  518. else:
  519. attempt = (now >= self.retryTime)
  520. if attempt:
  521. try:
  522. self.sock = self.makeSocket()
  523. self.retryTime = None # next time, no delay before trying
  524. except OSError:
  525. #Creation failed, so set the retry time and return.
  526. if self.retryTime is None:
  527. self.retryPeriod = self.retryStart
  528. else:
  529. self.retryPeriod = self.retryPeriod * self.retryFactor
  530. if self.retryPeriod > self.retryMax:
  531. self.retryPeriod = self.retryMax
  532. self.retryTime = now + self.retryPeriod
  533. def send(self, s):
  534. """
  535. Send a pickled string to the socket.
  536. This function allows for partial sends which can happen when the
  537. network is busy.
  538. """
  539. if self.sock is None:
  540. self.createSocket()
  541. #self.sock can be None either because we haven't reached the retry
  542. #time yet, or because we have reached the retry time and retried,
  543. #but are still unable to connect.
  544. if self.sock:
  545. try:
  546. self.sock.sendall(s)
  547. except OSError: #pragma: no cover
  548. self.sock.close()
  549. self.sock = None # so we can call createSocket next time
  550. def makePickle(self, record):
  551. """
  552. Pickles the record in binary format with a length prefix, and
  553. returns it ready for transmission across the socket.
  554. """
  555. ei = record.exc_info
  556. if ei:
  557. # just to get traceback text into record.exc_text ...
  558. dummy = self.format(record)
  559. # See issue #14436: If msg or args are objects, they may not be
  560. # available on the receiving end. So we convert the msg % args
  561. # to a string, save it as msg and zap the args.
  562. d = dict(record.__dict__)
  563. d['msg'] = record.getMessage()
  564. d['args'] = None
  565. d['exc_info'] = None
  566. # Issue #25685: delete 'message' if present: redundant with 'msg'
  567. d.pop('message', None)
  568. s = pickle.dumps(d, 1)
  569. slen = struct.pack(">L", len(s))
  570. return slen + s
  571. def handleError(self, record):
  572. """
  573. Handle an error during logging.
  574. An error has occurred during logging. Most likely cause -
  575. connection lost. Close the socket so that we can retry on the
  576. next event.
  577. """
  578. if self.closeOnError and self.sock:
  579. self.sock.close()
  580. self.sock = None #try to reconnect next time
  581. else:
  582. logging.Handler.handleError(self, record)
  583. def emit(self, record):
  584. """
  585. Emit a record.
  586. Pickles the record and writes it to the socket in binary format.
  587. If there is an error with the socket, silently drop the packet.
  588. If there was a problem with the socket, re-establishes the
  589. socket.
  590. """
  591. try:
  592. s = self.makePickle(record)
  593. self.send(s)
  594. except Exception:
  595. self.handleError(record)
  596. def close(self):
  597. """
  598. Closes the socket.
  599. """
  600. self.acquire()
  601. try:
  602. sock = self.sock
  603. if sock:
  604. self.sock = None
  605. sock.close()
  606. logging.Handler.close(self)
  607. finally:
  608. self.release()
  609. class DatagramHandler(SocketHandler):
  610. """
  611. A handler class which writes logging records, in pickle format, to
  612. a datagram socket. The pickle which is sent is that of the LogRecord's
  613. attribute dictionary (__dict__), so that the receiver does not need to
  614. have the logging module installed in order to process the logging event.
  615. To unpickle the record at the receiving end into a LogRecord, use the
  616. makeLogRecord function.
  617. """
  618. def __init__(self, host, port):
  619. """
  620. Initializes the handler with a specific host address and port.
  621. """
  622. SocketHandler.__init__(self, host, port)
  623. self.closeOnError = False
  624. def makeSocket(self):
  625. """
  626. The factory method of SocketHandler is here overridden to create
  627. a UDP socket (SOCK_DGRAM).
  628. """
  629. if self.port is None:
  630. family = socket.AF_UNIX
  631. else:
  632. family = socket.AF_INET
  633. s = socket.socket(family, socket.SOCK_DGRAM)
  634. return s
  635. def send(self, s):
  636. """
  637. Send a pickled string to a socket.
  638. This function no longer allows for partial sends which can happen
  639. when the network is busy - UDP does not guarantee delivery and
  640. can deliver packets out of sequence.
  641. """
  642. if self.sock is None:
  643. self.createSocket()
  644. self.sock.sendto(s, self.address)
  645. class SysLogHandler(logging.Handler):
  646. """
  647. A handler class which sends formatted logging records to a syslog
  648. server. Based on Sam Rushing's syslog module:
  649. http://www.nightmare.com/squirl/python-ext/misc/syslog.py
  650. Contributed by Nicolas Untz (after which minor refactoring changes
  651. have been made).
  652. """
  653. # from <linux/sys/syslog.h>:
  654. # ======================================================================
  655. # priorities/facilities are encoded into a single 32-bit quantity, where
  656. # the bottom 3 bits are the priority (0-7) and the top 28 bits are the
  657. # facility (0-big number). Both the priorities and the facilities map
  658. # roughly one-to-one to strings in the syslogd(8) source code. This
  659. # mapping is included in this file.
  660. #
  661. # priorities (these are ordered)
  662. LOG_EMERG = 0 # system is unusable
  663. LOG_ALERT = 1 # action must be taken immediately
  664. LOG_CRIT = 2 # critical conditions
  665. LOG_ERR = 3 # error conditions
  666. LOG_WARNING = 4 # warning conditions
  667. LOG_NOTICE = 5 # normal but significant condition
  668. LOG_INFO = 6 # informational
  669. LOG_DEBUG = 7 # debug-level messages
  670. # facility codes
  671. LOG_KERN = 0 # kernel messages
  672. LOG_USER = 1 # random user-level messages
  673. LOG_MAIL = 2 # mail system
  674. LOG_DAEMON = 3 # system daemons
  675. LOG_AUTH = 4 # security/authorization messages
  676. LOG_SYSLOG = 5 # messages generated internally by syslogd
  677. LOG_LPR = 6 # line printer subsystem
  678. LOG_NEWS = 7 # network news subsystem
  679. LOG_UUCP = 8 # UUCP subsystem
  680. LOG_CRON = 9 # clock daemon
  681. LOG_AUTHPRIV = 10 # security/authorization messages (private)
  682. LOG_FTP = 11 # FTP daemon
  683. LOG_NTP = 12 # NTP subsystem
  684. LOG_SECURITY = 13 # Log audit
  685. LOG_CONSOLE = 14 # Log alert
  686. LOG_SOLCRON = 15 # Scheduling daemon (Solaris)
  687. # other codes through 15 reserved for system use
  688. LOG_LOCAL0 = 16 # reserved for local use
  689. LOG_LOCAL1 = 17 # reserved for local use
  690. LOG_LOCAL2 = 18 # reserved for local use
  691. LOG_LOCAL3 = 19 # reserved for local use
  692. LOG_LOCAL4 = 20 # reserved for local use
  693. LOG_LOCAL5 = 21 # reserved for local use
  694. LOG_LOCAL6 = 22 # reserved for local use
  695. LOG_LOCAL7 = 23 # reserved for local use
  696. priority_names = {
  697. "alert": LOG_ALERT,
  698. "crit": LOG_CRIT,
  699. "critical": LOG_CRIT,
  700. "debug": LOG_DEBUG,
  701. "emerg": LOG_EMERG,
  702. "err": LOG_ERR,
  703. "error": LOG_ERR, # DEPRECATED
  704. "info": LOG_INFO,
  705. "notice": LOG_NOTICE,
  706. "panic": LOG_EMERG, # DEPRECATED
  707. "warn": LOG_WARNING, # DEPRECATED
  708. "warning": LOG_WARNING,
  709. }
  710. facility_names = {
  711. "auth": LOG_AUTH,
  712. "authpriv": LOG_AUTHPRIV,
  713. "console": LOG_CONSOLE,
  714. "cron": LOG_CRON,
  715. "daemon": LOG_DAEMON,
  716. "ftp": LOG_FTP,
  717. "kern": LOG_KERN,
  718. "lpr": LOG_LPR,
  719. "mail": LOG_MAIL,
  720. "news": LOG_NEWS,
  721. "ntp": LOG_NTP,
  722. "security": LOG_SECURITY,
  723. "solaris-cron": LOG_SOLCRON,
  724. "syslog": LOG_SYSLOG,
  725. "user": LOG_USER,
  726. "uucp": LOG_UUCP,
  727. "local0": LOG_LOCAL0,
  728. "local1": LOG_LOCAL1,
  729. "local2": LOG_LOCAL2,
  730. "local3": LOG_LOCAL3,
  731. "local4": LOG_LOCAL4,
  732. "local5": LOG_LOCAL5,
  733. "local6": LOG_LOCAL6,
  734. "local7": LOG_LOCAL7,
  735. }
  736. #The map below appears to be trivially lowercasing the key. However,
  737. #there's more to it than meets the eye - in some locales, lowercasing
  738. #gives unexpected results. See SF #1524081: in the Turkish locale,
  739. #"INFO".lower() != "info"
  740. priority_map = {
  741. "DEBUG" : "debug",
  742. "INFO" : "info",
  743. "WARNING" : "warning",
  744. "ERROR" : "error",
  745. "CRITICAL" : "critical"
  746. }
  747. def __init__(self, address=('localhost', SYSLOG_UDP_PORT),
  748. facility=LOG_USER, socktype=None):
  749. """
  750. Initialize a handler.
  751. If address is specified as a string, a UNIX socket is used. To log to a
  752. local syslogd, "SysLogHandler(address="/dev/log")" can be used.
  753. If facility is not specified, LOG_USER is used. If socktype is
  754. specified as socket.SOCK_DGRAM or socket.SOCK_STREAM, that specific
  755. socket type will be used. For Unix sockets, you can also specify a
  756. socktype of None, in which case socket.SOCK_DGRAM will be used, falling
  757. back to socket.SOCK_STREAM.
  758. """
  759. logging.Handler.__init__(self)
  760. self.address = address
  761. self.facility = facility
  762. self.socktype = socktype
  763. if isinstance(address, str):
  764. self.unixsocket = True
  765. # Syslog server may be unavailable during handler initialisation.
  766. # C's openlog() function also ignores connection errors.
  767. # Moreover, we ignore these errors while logging, so it not worse
  768. # to ignore it also here.
  769. try:
  770. self._connect_unixsocket(address)
  771. except OSError:
  772. pass
  773. else:
  774. self.unixsocket = False
  775. if socktype is None:
  776. socktype = socket.SOCK_DGRAM
  777. host, port = address
  778. ress = socket.getaddrinfo(host, port, 0, socktype)
  779. if not ress:
  780. raise OSError("getaddrinfo returns an empty list")
  781. for res in ress:
  782. af, socktype, proto, _, sa = res
  783. err = sock = None
  784. try:
  785. sock = socket.socket(af, socktype, proto)
  786. if socktype == socket.SOCK_STREAM:
  787. sock.connect(sa)
  788. break
  789. except OSError as exc:
  790. err = exc
  791. if sock is not None:
  792. sock.close()
  793. if err is not None:
  794. raise err
  795. self.socket = sock
  796. self.socktype = socktype
  797. def _connect_unixsocket(self, address):
  798. use_socktype = self.socktype
  799. if use_socktype is None:
  800. use_socktype = socket.SOCK_DGRAM
  801. self.socket = socket.socket(socket.AF_UNIX, use_socktype)
  802. try:
  803. self.socket.connect(address)
  804. # it worked, so set self.socktype to the used type
  805. self.socktype = use_socktype
  806. except OSError:
  807. self.socket.close()
  808. if self.socktype is not None:
  809. # user didn't specify falling back, so fail
  810. raise
  811. use_socktype = socket.SOCK_STREAM
  812. self.socket = socket.socket(socket.AF_UNIX, use_socktype)
  813. try:
  814. self.socket.connect(address)
  815. # it worked, so set self.socktype to the used type
  816. self.socktype = use_socktype
  817. except OSError:
  818. self.socket.close()
  819. raise
  820. def encodePriority(self, facility, priority):
  821. """
  822. Encode the facility and priority. You can pass in strings or
  823. integers - if strings are passed, the facility_names and
  824. priority_names mapping dictionaries are used to convert them to
  825. integers.
  826. """
  827. if isinstance(facility, str):
  828. facility = self.facility_names[facility]
  829. if isinstance(priority, str):
  830. priority = self.priority_names[priority]
  831. return (facility << 3) | priority
  832. def close(self):
  833. """
  834. Closes the socket.
  835. """
  836. self.acquire()
  837. try:
  838. self.socket.close()
  839. logging.Handler.close(self)
  840. finally:
  841. self.release()
  842. def mapPriority(self, levelName):
  843. """
  844. Map a logging level name to a key in the priority_names map.
  845. This is useful in two scenarios: when custom levels are being
  846. used, and in the case where you can't do a straightforward
  847. mapping by lowercasing the logging level name because of locale-
  848. specific issues (see SF #1524081).
  849. """
  850. return self.priority_map.get(levelName, "warning")
  851. ident = '' # prepended to all messages
  852. append_nul = True # some old syslog daemons expect a NUL terminator
  853. def emit(self, record):
  854. """
  855. Emit a record.
  856. The record is formatted, and then sent to the syslog server. If
  857. exception information is present, it is NOT sent to the server.
  858. """
  859. try:
  860. msg = self.format(record)
  861. if self.ident:
  862. msg = self.ident + msg
  863. if self.append_nul:
  864. msg += '\000'
  865. # We need to convert record level to lowercase, maybe this will
  866. # change in the future.
  867. prio = '<%d>' % self.encodePriority(self.facility,
  868. self.mapPriority(record.levelname))
  869. prio = prio.encode('utf-8')
  870. # Message is a string. Convert to bytes as required by RFC 5424
  871. msg = msg.encode('utf-8')
  872. msg = prio + msg
  873. if self.unixsocket:
  874. try:
  875. self.socket.send(msg)
  876. except OSError:
  877. self.socket.close()
  878. self._connect_unixsocket(self.address)
  879. self.socket.send(msg)
  880. elif self.socktype == socket.SOCK_DGRAM:
  881. self.socket.sendto(msg, self.address)
  882. else:
  883. self.socket.sendall(msg)
  884. except Exception:
  885. self.handleError(record)
  886. class SMTPHandler(logging.Handler):
  887. """
  888. A handler class which sends an SMTP email for each logging event.
  889. """
  890. def __init__(self, mailhost, fromaddr, toaddrs, subject,
  891. credentials=None, secure=None, timeout=5.0):
  892. """
  893. Initialize the handler.
  894. Initialize the instance with the from and to addresses and subject
  895. line of the email. To specify a non-standard SMTP port, use the
  896. (host, port) tuple format for the mailhost argument. To specify
  897. authentication credentials, supply a (username, password) tuple
  898. for the credentials argument. To specify the use of a secure
  899. protocol (TLS), pass in a tuple for the secure argument. This will
  900. only be used when authentication credentials are supplied. The tuple
  901. will be either an empty tuple, or a single-value tuple with the name
  902. of a keyfile, or a 2-value tuple with the names of the keyfile and
  903. certificate file. (This tuple is passed to the `starttls` method).
  904. A timeout in seconds can be specified for the SMTP connection (the
  905. default is one second).
  906. """
  907. logging.Handler.__init__(self)
  908. if isinstance(mailhost, (list, tuple)):
  909. self.mailhost, self.mailport = mailhost
  910. else:
  911. self.mailhost, self.mailport = mailhost, None
  912. if isinstance(credentials, (list, tuple)):
  913. self.username, self.password = credentials
  914. else:
  915. self.username = None
  916. self.fromaddr = fromaddr
  917. if isinstance(toaddrs, str):
  918. toaddrs = [toaddrs]
  919. self.toaddrs = toaddrs
  920. self.subject = subject
  921. self.secure = secure
  922. self.timeout = timeout
  923. def getSubject(self, record):
  924. """
  925. Determine the subject for the email.
  926. If you want to specify a subject line which is record-dependent,
  927. override this method.
  928. """
  929. return self.subject
  930. def emit(self, record):
  931. """
  932. Emit a record.
  933. Format the record and send it to the specified addressees.
  934. """
  935. try:
  936. import smtplib
  937. from email.message import EmailMessage
  938. import email.utils
  939. port = self.mailport
  940. if not port:
  941. port = smtplib.SMTP_PORT
  942. smtp = smtplib.SMTP(self.mailhost, port, timeout=self.timeout)
  943. msg = EmailMessage()
  944. msg['From'] = self.fromaddr
  945. msg['To'] = ','.join(self.toaddrs)
  946. msg['Subject'] = self.getSubject(record)
  947. msg['Date'] = email.utils.localtime()
  948. msg.set_content(self.format(record))
  949. if self.username:
  950. if self.secure is not None:
  951. smtp.ehlo()
  952. smtp.starttls(*self.secure)
  953. smtp.ehlo()
  954. smtp.login(self.username, self.password)
  955. smtp.send_message(msg)
  956. smtp.quit()
  957. except Exception:
  958. self.handleError(record)
  959. class NTEventLogHandler(logging.Handler):
  960. """
  961. A handler class which sends events to the NT Event Log. Adds a
  962. registry entry for the specified application name. If no dllname is
  963. provided, win32service.pyd (which contains some basic message
  964. placeholders) is used. Note that use of these placeholders will make
  965. your event logs big, as the entire message source is held in the log.
  966. If you want slimmer logs, you have to pass in the name of your own DLL
  967. which contains the message definitions you want to use in the event log.
  968. """
  969. def __init__(self, appname, dllname=None, logtype="Application"):
  970. logging.Handler.__init__(self)
  971. try:
  972. import win32evtlogutil, win32evtlog
  973. self.appname = appname
  974. self._welu = win32evtlogutil
  975. if not dllname:
  976. dllname = os.path.split(self._welu.__file__)
  977. dllname = os.path.split(dllname[0])
  978. dllname = os.path.join(dllname[0], r'win32service.pyd')
  979. self.dllname = dllname
  980. self.logtype = logtype
  981. self._welu.AddSourceToRegistry(appname, dllname, logtype)
  982. self.deftype = win32evtlog.EVENTLOG_ERROR_TYPE
  983. self.typemap = {
  984. logging.DEBUG : win32evtlog.EVENTLOG_INFORMATION_TYPE,
  985. logging.INFO : win32evtlog.EVENTLOG_INFORMATION_TYPE,
  986. logging.WARNING : win32evtlog.EVENTLOG_WARNING_TYPE,
  987. logging.ERROR : win32evtlog.EVENTLOG_ERROR_TYPE,
  988. logging.CRITICAL: win32evtlog.EVENTLOG_ERROR_TYPE,
  989. }
  990. except ImportError:
  991. print("The Python Win32 extensions for NT (service, event "\
  992. "logging) appear not to be available.")
  993. self._welu = None
  994. def getMessageID(self, record):
  995. """
  996. Return the message ID for the event record. If you are using your
  997. own messages, you could do this by having the msg passed to the
  998. logger being an ID rather than a formatting string. Then, in here,
  999. you could use a dictionary lookup to get the message ID. This
  1000. version returns 1, which is the base message ID in win32service.pyd.
  1001. """
  1002. return 1
  1003. def getEventCategory(self, record):
  1004. """
  1005. Return the event category for the record.
  1006. Override this if you want to specify your own categories. This version
  1007. returns 0.
  1008. """
  1009. return 0
  1010. def getEventType(self, record):
  1011. """
  1012. Return the event type for the record.
  1013. Override this if you want to specify your own types. This version does
  1014. a mapping using the handler's typemap attribute, which is set up in
  1015. __init__() to a dictionary which contains mappings for DEBUG, INFO,
  1016. WARNING, ERROR and CRITICAL. If you are using your own levels you will
  1017. either need to override this method or place a suitable dictionary in
  1018. the handler's typemap attribute.
  1019. """
  1020. return self.typemap.get(record.levelno, self.deftype)
  1021. def emit(self, record):
  1022. """
  1023. Emit a record.
  1024. Determine the message ID, event category and event type. Then
  1025. log the message in the NT event log.
  1026. """
  1027. if self._welu:
  1028. try:
  1029. id = self.getMessageID(record)
  1030. cat = self.getEventCategory(record)
  1031. type = self.getEventType(record)
  1032. msg = self.format(record)
  1033. self._welu.ReportEvent(self.appname, id, cat, type, [msg])
  1034. except Exception:
  1035. self.handleError(record)
  1036. def close(self):
  1037. """
  1038. Clean up this handler.
  1039. You can remove the application name from the registry as a
  1040. source of event log entries. However, if you do this, you will
  1041. not be able to see the events as you intended in the Event Log
  1042. Viewer - it needs to be able to access the registry to get the
  1043. DLL name.
  1044. """
  1045. #self._welu.RemoveSourceFromRegistry(self.appname, self.logtype)
  1046. logging.Handler.close(self)
  1047. class HTTPHandler(logging.Handler):
  1048. """
  1049. A class which sends records to a web server, using either GET or
  1050. POST semantics.
  1051. """
  1052. def __init__(self, host, url, method="GET", secure=False, credentials=None,
  1053. context=None):
  1054. """
  1055. Initialize the instance with the host, the request URL, and the method
  1056. ("GET" or "POST")
  1057. """
  1058. logging.Handler.__init__(self)
  1059. method = method.upper()
  1060. if method not in ["GET", "POST"]:
  1061. raise ValueError("method must be GET or POST")
  1062. if not secure and context is not None:
  1063. raise ValueError("context parameter only makes sense "
  1064. "with secure=True")
  1065. self.host = host
  1066. self.url = url
  1067. self.method = method
  1068. self.secure = secure
  1069. self.credentials = credentials
  1070. self.context = context
  1071. def mapLogRecord(self, record):
  1072. """
  1073. Default implementation of mapping the log record into a dict
  1074. that is sent as the CGI data. Overwrite in your class.
  1075. Contributed by Franz Glasner.
  1076. """
  1077. return record.__dict__
  1078. def getConnection(self, host, secure):
  1079. """
  1080. get a HTTP[S]Connection.
  1081. Override when a custom connection is required, for example if
  1082. there is a proxy.
  1083. """
  1084. import http.client
  1085. if secure:
  1086. connection = http.client.HTTPSConnection(host, context=self.context)
  1087. else:
  1088. connection = http.client.HTTPConnection(host)
  1089. return connection
  1090. def emit(self, record):
  1091. """
  1092. Emit a record.
  1093. Send the record to the web server as a percent-encoded dictionary
  1094. """
  1095. try:
  1096. import urllib.parse
  1097. host = self.host
  1098. h = self.getConnection(host, self.secure)
  1099. url = self.url
  1100. data = urllib.parse.urlencode(self.mapLogRecord(record))
  1101. if self.method == "GET":
  1102. if (url.find('?') >= 0):
  1103. sep = '&'
  1104. else:
  1105. sep = '?'
  1106. url = url + "%c%s" % (sep, data)
  1107. h.putrequest(self.method, url)
  1108. # support multiple hosts on one IP address...
  1109. # need to strip optional :port from host, if present
  1110. i = host.find(":")
  1111. if i >= 0:
  1112. host = host[:i]
  1113. # See issue #30904: putrequest call above already adds this header
  1114. # on Python 3.x.
  1115. # h.putheader("Host", host)
  1116. if self.method == "POST":
  1117. h.putheader("Content-type",
  1118. "application/x-www-form-urlencoded")
  1119. h.putheader("Content-length", str(len(data)))
  1120. if self.credentials:
  1121. import base64
  1122. s = ('%s:%s' % self.credentials).encode('utf-8')
  1123. s = 'Basic ' + base64.b64encode(s).strip().decode('ascii')
  1124. h.putheader('Authorization', s)
  1125. h.endheaders()
  1126. if self.method == "POST":
  1127. h.send(data.encode('utf-8'))
  1128. h.getresponse() #can't do anything with the result
  1129. except Exception:
  1130. self.handleError(record)
  1131. class BufferingHandler(logging.Handler):
  1132. """
  1133. A handler class which buffers logging records in memory. Whenever each
  1134. record is added to the buffer, a check is made to see if the buffer should
  1135. be flushed. If it should, then flush() is expected to do what's needed.
  1136. """
  1137. def __init__(self, capacity):
  1138. """
  1139. Initialize the handler with the buffer size.
  1140. """
  1141. logging.Handler.__init__(self)
  1142. self.capacity = capacity
  1143. self.buffer = []
  1144. def shouldFlush(self, record):
  1145. """
  1146. Should the handler flush its buffer?
  1147. Returns true if the buffer is up to capacity. This method can be
  1148. overridden to implement custom flushing strategies.
  1149. """
  1150. return (len(self.buffer) >= self.capacity)
  1151. def emit(self, record):
  1152. """
  1153. Emit a record.
  1154. Append the record. If shouldFlush() tells us to, call flush() to process
  1155. the buffer.
  1156. """
  1157. self.buffer.append(record)
  1158. if self.shouldFlush(record):
  1159. self.flush()
  1160. def flush(self):
  1161. """
  1162. Override to implement custom flushing behaviour.
  1163. This version just zaps the buffer to empty.
  1164. """
  1165. self.acquire()
  1166. try:
  1167. self.buffer.clear()
  1168. finally:
  1169. self.release()
  1170. def close(self):
  1171. """
  1172. Close the handler.
  1173. This version just flushes and chains to the parent class' close().
  1174. """
  1175. try:
  1176. self.flush()
  1177. finally:
  1178. logging.Handler.close(self)
  1179. class MemoryHandler(BufferingHandler):
  1180. """
  1181. A handler class which buffers logging records in memory, periodically
  1182. flushing them to a target handler. Flushing occurs whenever the buffer
  1183. is full, or when an event of a certain severity or greater is seen.
  1184. """
  1185. def __init__(self, capacity, flushLevel=logging.ERROR, target=None,
  1186. flushOnClose=True):
  1187. """
  1188. Initialize the handler with the buffer size, the level at which
  1189. flushing should occur and an optional target.
  1190. Note that without a target being set either here or via setTarget(),
  1191. a MemoryHandler is no use to anyone!
  1192. The ``flushOnClose`` argument is ``True`` for backward compatibility
  1193. reasons - the old behaviour is that when the handler is closed, the
  1194. buffer is flushed, even if the flush level hasn't been exceeded nor the
  1195. capacity exceeded. To prevent this, set ``flushOnClose`` to ``False``.
  1196. """
  1197. BufferingHandler.__init__(self, capacity)
  1198. self.flushLevel = flushLevel
  1199. self.target = target
  1200. # See Issue #26559 for why this has been added
  1201. self.flushOnClose = flushOnClose
  1202. def shouldFlush(self, record):
  1203. """
  1204. Check for buffer full or a record at the flushLevel or higher.
  1205. """
  1206. return (len(self.buffer) >= self.capacity) or \
  1207. (record.levelno >= self.flushLevel)
  1208. def setTarget(self, target):
  1209. """
  1210. Set the target handler for this handler.
  1211. """
  1212. self.acquire()
  1213. try:
  1214. self.target = target
  1215. finally:
  1216. self.release()
  1217. def flush(self):
  1218. """
  1219. For a MemoryHandler, flushing means just sending the buffered
  1220. records to the target, if there is one. Override if you want
  1221. different behaviour.
  1222. The record buffer is also cleared by this operation.
  1223. """
  1224. self.acquire()
  1225. try:
  1226. if self.target:
  1227. for record in self.buffer:
  1228. self.target.handle(record)
  1229. self.buffer.clear()
  1230. finally:
  1231. self.release()
  1232. def close(self):
  1233. """
  1234. Flush, if appropriately configured, set the target to None and lose the
  1235. buffer.
  1236. """
  1237. try:
  1238. if self.flushOnClose:
  1239. self.flush()
  1240. finally:
  1241. self.acquire()
  1242. try:
  1243. self.target = None
  1244. BufferingHandler.close(self)
  1245. finally:
  1246. self.release()
  1247. class QueueHandler(logging.Handler):
  1248. """
  1249. This handler sends events to a queue. Typically, it would be used together
  1250. with a multiprocessing Queue to centralise logging to file in one process
  1251. (in a multi-process application), so as to avoid file write contention
  1252. between processes.
  1253. This code is new in Python 3.2, but this class can be copy pasted into
  1254. user code for use with earlier Python versions.
  1255. """
  1256. def __init__(self, queue):
  1257. """
  1258. Initialise an instance, using the passed queue.
  1259. """
  1260. logging.Handler.__init__(self)
  1261. self.queue = queue
  1262. def enqueue(self, record):
  1263. """
  1264. Enqueue a record.
  1265. The base implementation uses put_nowait. You may want to override
  1266. this method if you want to use blocking, timeouts or custom queue
  1267. implementations.
  1268. """
  1269. self.queue.put_nowait(record)
  1270. def prepare(self, record):
  1271. """
  1272. Prepares a record for queuing. The object returned by this method is
  1273. enqueued.
  1274. The base implementation formats the record to merge the message
  1275. and arguments, and removes unpickleable items from the record
  1276. in-place.
  1277. You might want to override this method if you want to convert
  1278. the record to a dict or JSON string, or send a modified copy
  1279. of the record while leaving the original intact.
  1280. """
  1281. # The format operation gets traceback text into record.exc_text
  1282. # (if there's exception data), and also returns the formatted
  1283. # message. We can then use this to replace the original
  1284. # msg + args, as these might be unpickleable. We also zap the
  1285. # exc_info and exc_text attributes, as they are no longer
  1286. # needed and, if not None, will typically not be pickleable.
  1287. msg = self.format(record)
  1288. # bpo-35726: make copy of record to avoid affecting other handlers in the chain.
  1289. record = copy.copy(record)
  1290. record.message = msg
  1291. record.msg = msg
  1292. record.args = None
  1293. record.exc_info = None
  1294. record.exc_text = None
  1295. return record
  1296. def emit(self, record):
  1297. """
  1298. Emit a record.
  1299. Writes the LogRecord to the queue, preparing it for pickling first.
  1300. """
  1301. try:
  1302. self.enqueue(self.prepare(record))
  1303. except Exception:
  1304. self.handleError(record)
  1305. class QueueListener(object):
  1306. """
  1307. This class implements an internal threaded listener which watches for
  1308. LogRecords being added to a queue, removes them and passes them to a
  1309. list of handlers for processing.
  1310. """
  1311. _sentinel = None
  1312. def __init__(self, queue, *handlers, respect_handler_level=False):
  1313. """
  1314. Initialise an instance with the specified queue and
  1315. handlers.
  1316. """
  1317. self.queue = queue
  1318. self.handlers = handlers
  1319. self._thread = None
  1320. self.respect_handler_level = respect_handler_level
  1321. def dequeue(self, block):
  1322. """
  1323. Dequeue a record and return it, optionally blocking.
  1324. The base implementation uses get. You may want to override this method
  1325. if you want to use timeouts or work with custom queue implementations.
  1326. """
  1327. return self.queue.get(block)
  1328. def start(self):
  1329. """
  1330. Start the listener.
  1331. This starts up a background thread to monitor the queue for
  1332. LogRecords to process.
  1333. """
  1334. self._thread = t = threading.Thread(target=self._monitor)
  1335. t.daemon = True
  1336. t.start()
  1337. def prepare(self, record):
  1338. """
  1339. Prepare a record for handling.
  1340. This method just returns the passed-in record. You may want to
  1341. override this method if you need to do any custom marshalling or
  1342. manipulation of the record before passing it to the handlers.
  1343. """
  1344. return record
  1345. def handle(self, record):
  1346. """
  1347. Handle a record.
  1348. This just loops through the handlers offering them the record
  1349. to handle.
  1350. """
  1351. record = self.prepare(record)
  1352. for handler in self.handlers:
  1353. if not self.respect_handler_level:
  1354. process = True
  1355. else:
  1356. process = record.levelno >= handler.level
  1357. if process:
  1358. handler.handle(record)
  1359. def _monitor(self):
  1360. """
  1361. Monitor the queue for records, and ask the handler
  1362. to deal with them.
  1363. This method runs on a separate, internal thread.
  1364. The thread will terminate if it sees a sentinel object in the queue.
  1365. """
  1366. q = self.queue
  1367. has_task_done = hasattr(q, 'task_done')
  1368. while True:
  1369. try:
  1370. record = self.dequeue(True)
  1371. if record is self._sentinel:
  1372. if has_task_done:
  1373. q.task_done()
  1374. break
  1375. self.handle(record)
  1376. if has_task_done:
  1377. q.task_done()
  1378. except queue.Empty:
  1379. break
  1380. def enqueue_sentinel(self):
  1381. """
  1382. This is used to enqueue the sentinel record.
  1383. The base implementation uses put_nowait. You may want to override this
  1384. method if you want to use timeouts or work with custom queue
  1385. implementations.
  1386. """
  1387. self.queue.put_nowait(self._sentinel)
  1388. def stop(self):
  1389. """
  1390. Stop the listener.
  1391. This asks the thread to terminate, and then waits for it to do so.
  1392. Note that if you don't call this before your application exits, there
  1393. may be some records still left on the queue, which won't be processed.
  1394. """
  1395. self.enqueue_sentinel()
  1396. self._thread.join()
  1397. self._thread = None