Debian Codegraph @

lib-python/3/logging/handlers.py

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