1:mod:`logging.handlers` --- Logging handlers
2============================================
3
4.. module:: logging.handlers
5   :synopsis: Handlers for the logging module.
6
7.. moduleauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
8.. sectionauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
9
10**Source code:** :source:`Lib/logging/handlers.py`
11
12.. sidebar:: Important
13
14   This page contains only reference information. For tutorials,
15   please see
16
17   * :ref:`Basic Tutorial <logging-basic-tutorial>`
18   * :ref:`Advanced Tutorial <logging-advanced-tutorial>`
19   * :ref:`Logging Cookbook <logging-cookbook>`
20
21--------------
22
23.. currentmodule:: logging
24
25The following useful handlers are provided in the package. Note that three of
26the handlers (:class:`StreamHandler`, :class:`FileHandler` and
27:class:`NullHandler`) are actually defined in the :mod:`logging` module itself,
28but have been documented here along with the other handlers.
29
30.. _stream-handler:
31
32StreamHandler
33^^^^^^^^^^^^^
34
35The :class:`StreamHandler` class, located in the core :mod:`logging` package,
36sends logging output to streams such as *sys.stdout*, *sys.stderr* or any
37file-like object (or, more precisely, any object which supports :meth:`write`
38and :meth:`flush` methods).
39
40
41.. class:: StreamHandler(stream=None)
42
43   Returns a new instance of the :class:`StreamHandler` class. If *stream* is
44   specified, the instance will use it for logging output; otherwise, *sys.stderr*
45   will be used.
46
47
48   .. method:: emit(record)
49
50      If a formatter is specified, it is used to format the record. The record
51      is then written to the stream followed by :attr:`terminator`. If exception information
52      is present, it is formatted using :func:`traceback.print_exception` and
53      appended to the stream.
54
55
56   .. method:: flush()
57
58      Flushes the stream by calling its :meth:`flush` method. Note that the
59      :meth:`close` method is inherited from :class:`~logging.Handler` and so
60      does no output, so an explicit :meth:`flush` call may be needed at times.
61
62   .. method:: setStream(stream)
63
64      Sets the instance's stream to the specified value, if it is different.
65      The old stream is flushed before the new stream is set.
66
67      :param stream: The stream that the handler should use.
68
69      :return: the old stream, if the stream was changed, or *None* if it wasn't.
70
71      .. versionadded:: 3.7
72
73   .. attribute:: terminator
74
75      String used as the terminator when writing a formatted record to a stream.
76      Default value is ``'\n'``.
77
78      If you don't want a newline termination, you can set the handler instance's
79      ``terminator`` attribute to the empty string.
80
81      In earlier versions, the terminator was hardcoded as ``'\n'``.
82
83      .. versionadded:: 3.2
84
85
86.. _file-handler:
87
88FileHandler
89^^^^^^^^^^^
90
91The :class:`FileHandler` class, located in the core :mod:`logging` package,
92sends logging output to a disk file.  It inherits the output functionality from
93:class:`StreamHandler`.
94
95
96.. class:: FileHandler(filename, mode='a', encoding=None, delay=False, errors=None)
97
98   Returns a new instance of the :class:`FileHandler` class. The specified file is
99   opened and used as the stream for logging. If *mode* is not specified,
100   :const:`'a'` is used.  If *encoding* is not ``None``, it is used to open the file
101   with that encoding.  If *delay* is true, then file opening is deferred until the
102   first call to :meth:`emit`. By default, the file grows indefinitely. If
103   *errors* is specified, it's used to determine how encoding errors are handled.
104
105   .. versionchanged:: 3.6
106      As well as string values, :class:`~pathlib.Path` objects are also accepted
107      for the *filename* argument.
108
109   .. versionchanged:: 3.9
110      The *errors* parameter was added.
111
112   .. method:: close()
113
114      Closes the file.
115
116   .. method:: emit(record)
117
118      Outputs the record to the file.
119
120      Note that if the file was closed due to logging shutdown at exit and the file
121      mode is 'w', the record will not be emitted (see :issue:`42378`).
122
123
124.. _null-handler:
125
126NullHandler
127^^^^^^^^^^^
128
129.. versionadded:: 3.1
130
131The :class:`NullHandler` class, located in the core :mod:`logging` package,
132does not do any formatting or output. It is essentially a 'no-op' handler
133for use by library developers.
134
135.. class:: NullHandler()
136
137   Returns a new instance of the :class:`NullHandler` class.
138
139   .. method:: emit(record)
140
141      This method does nothing.
142
143   .. method:: handle(record)
144
145      This method does nothing.
146
147   .. method:: createLock()
148
149      This method returns ``None`` for the lock, since there is no
150      underlying I/O to which access needs to be serialized.
151
152
153See :ref:`library-config` for more information on how to use
154:class:`NullHandler`.
155
156.. _watched-file-handler:
157
158WatchedFileHandler
159^^^^^^^^^^^^^^^^^^
160
161.. currentmodule:: logging.handlers
162
163The :class:`WatchedFileHandler` class, located in the :mod:`logging.handlers`
164module, is a :class:`FileHandler` which watches the file it is logging to. If
165the file changes, it is closed and reopened using the file name.
166
167A file change can happen because of usage of programs such as *newsyslog* and
168*logrotate* which perform log file rotation. This handler, intended for use
169under Unix/Linux, watches the file to see if it has changed since the last emit.
170(A file is deemed to have changed if its device or inode have changed.) If the
171file has changed, the old file stream is closed, and the file opened to get a
172new stream.
173
174This handler is not appropriate for use under Windows, because under Windows
175open log files cannot be moved or renamed - logging opens the files with
176exclusive locks - and so there is no need for such a handler. Furthermore,
177*ST_INO* is not supported under Windows; :func:`~os.stat` always returns zero
178for this value.
179
180
181.. class:: WatchedFileHandler(filename, mode='a', encoding=None, delay=False, errors=None)
182
183   Returns a new instance of the :class:`WatchedFileHandler` class. The specified
184   file is opened and used as the stream for logging. If *mode* is not specified,
185   :const:`'a'` is used.  If *encoding* is not ``None``, it is used to open the file
186   with that encoding.  If *delay* is true, then file opening is deferred until the
187   first call to :meth:`emit`.  By default, the file grows indefinitely. If
188   *errors* is provided, it determines how encoding errors are handled.
189
190   .. versionchanged:: 3.6
191      As well as string values, :class:`~pathlib.Path` objects are also accepted
192      for the *filename* argument.
193
194   .. versionchanged:: 3.9
195      The *errors* parameter was added.
196
197   .. method:: reopenIfNeeded()
198
199      Checks to see if the file has changed.  If it has, the existing stream is
200      flushed and closed and the file opened again, typically as a precursor to
201      outputting the record to the file.
202
203      .. versionadded:: 3.6
204
205
206   .. method:: emit(record)
207
208      Outputs the record to the file, but first calls :meth:`reopenIfNeeded` to
209      reopen the file if it has changed.
210
211.. _base-rotating-handler:
212
213BaseRotatingHandler
214^^^^^^^^^^^^^^^^^^^
215
216The :class:`BaseRotatingHandler` class, located in the :mod:`logging.handlers`
217module, is the base class for the rotating file handlers,
218:class:`RotatingFileHandler` and :class:`TimedRotatingFileHandler`. You should
219not need to instantiate this class, but it has attributes and methods you may
220need to override.
221
222.. class:: BaseRotatingHandler(filename, mode, encoding=None, delay=False, errors=None)
223
224   The parameters are as for :class:`FileHandler`. The attributes are:
225
226   .. attribute:: namer
227
228      If this attribute is set to a callable, the :meth:`rotation_filename`
229      method delegates to this callable. The parameters passed to the callable
230      are those passed to :meth:`rotation_filename`.
231
232      .. note:: The namer function is called quite a few times during rollover,
233         so it should be as simple and as fast as possible. It should also
234         return the same output every time for a given input, otherwise the
235         rollover behaviour may not work as expected.
236
237      .. versionadded:: 3.3
238
239
240   .. attribute:: BaseRotatingHandler.rotator
241
242      If this attribute is set to a callable, the :meth:`rotate` method
243      delegates to this callable.  The parameters passed to the callable are
244      those passed to :meth:`rotate`.
245
246      .. versionadded:: 3.3
247
248   .. method:: BaseRotatingHandler.rotation_filename(default_name)
249
250      Modify the filename of a log file when rotating.
251
252      This is provided so that a custom filename can be provided.
253
254      The default implementation calls the 'namer' attribute of the handler,
255      if it's callable, passing the default name to it. If the attribute isn't
256      callable (the default is ``None``), the name is returned unchanged.
257
258      :param default_name: The default name for the log file.
259
260      .. versionadded:: 3.3
261
262
263   .. method:: BaseRotatingHandler.rotate(source, dest)
264
265      When rotating, rotate the current log.
266
267      The default implementation calls the 'rotator' attribute of the handler,
268      if it's callable, passing the source and dest arguments to it. If the
269      attribute isn't callable (the default is ``None``), the source is simply
270      renamed to the destination.
271
272      :param source: The source filename. This is normally the base
273                     filename, e.g. 'test.log'.
274      :param dest:   The destination filename. This is normally
275                     what the source is rotated to, e.g. 'test.log.1'.
276
277      .. versionadded:: 3.3
278
279The reason the attributes exist is to save you having to subclass - you can use
280the same callables for instances of :class:`RotatingFileHandler` and
281:class:`TimedRotatingFileHandler`. If either the namer or rotator callable
282raises an exception, this will be handled in the same way as any other
283exception during an :meth:`emit` call, i.e. via the :meth:`handleError` method
284of the handler.
285
286If you need to make more significant changes to rotation processing, you can
287override the methods.
288
289For an example, see :ref:`cookbook-rotator-namer`.
290
291
292.. _rotating-file-handler:
293
294RotatingFileHandler
295^^^^^^^^^^^^^^^^^^^
296
297The :class:`RotatingFileHandler` class, located in the :mod:`logging.handlers`
298module, supports rotation of disk log files.
299
300
301.. class:: RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=False, errors=None)
302
303   Returns a new instance of the :class:`RotatingFileHandler` class. The specified
304   file is opened and used as the stream for logging. If *mode* is not specified,
305   ``'a'`` is used.  If *encoding* is not ``None``, it is used to open the file
306   with that encoding.  If *delay* is true, then file opening is deferred until the
307   first call to :meth:`emit`.  By default, the file grows indefinitely. If
308   *errors* is provided, it determines how encoding errors are handled.
309
310   You can use the *maxBytes* and *backupCount* values to allow the file to
311   :dfn:`rollover` at a predetermined size. When the size is about to be exceeded,
312   the file is closed and a new file is silently opened for output. Rollover occurs
313   whenever the current log file is nearly *maxBytes* in length; but if either of
314   *maxBytes* or *backupCount* is zero, rollover never occurs, so you generally want
315   to set *backupCount* to at least 1, and have a non-zero *maxBytes*.
316   When *backupCount* is non-zero, the system will save old log files by appending
317   the extensions '.1', '.2' etc., to the filename. For example, with a *backupCount*
318   of 5 and a base file name of :file:`app.log`, you would get :file:`app.log`,
319   :file:`app.log.1`, :file:`app.log.2`, up to :file:`app.log.5`. The file being
320   written to is always :file:`app.log`.  When this file is filled, it is closed
321   and renamed to :file:`app.log.1`, and if files :file:`app.log.1`,
322   :file:`app.log.2`, etc. exist, then they are renamed to :file:`app.log.2`,
323   :file:`app.log.3` etc. respectively.
324
325   .. versionchanged:: 3.6
326      As well as string values, :class:`~pathlib.Path` objects are also accepted
327      for the *filename* argument.
328
329   .. versionchanged:: 3.9
330      The *errors* parameter was added.
331
332   .. method:: doRollover()
333
334      Does a rollover, as described above.
335
336
337   .. method:: emit(record)
338
339      Outputs the record to the file, catering for rollover as described
340      previously.
341
342.. _timed-rotating-file-handler:
343
344TimedRotatingFileHandler
345^^^^^^^^^^^^^^^^^^^^^^^^
346
347The :class:`TimedRotatingFileHandler` class, located in the
348:mod:`logging.handlers` module, supports rotation of disk log files at certain
349timed intervals.
350
351
352.. class:: TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False, atTime=None, errors=None)
353
354   Returns a new instance of the :class:`TimedRotatingFileHandler` class. The
355   specified file is opened and used as the stream for logging. On rotating it also
356   sets the filename suffix. Rotating happens based on the product of *when* and
357   *interval*.
358
359   You can use the *when* to specify the type of *interval*. The list of possible
360   values is below.  Note that they are not case sensitive.
361
362   +----------------+----------------------------+-------------------------+
363   | Value          | Type of interval           | If/how *atTime* is used |
364   +================+============================+=========================+
365   | ``'S'``        | Seconds                    | Ignored                 |
366   +----------------+----------------------------+-------------------------+
367   | ``'M'``        | Minutes                    | Ignored                 |
368   +----------------+----------------------------+-------------------------+
369   | ``'H'``        | Hours                      | Ignored                 |
370   +----------------+----------------------------+-------------------------+
371   | ``'D'``        | Days                       | Ignored                 |
372   +----------------+----------------------------+-------------------------+
373   | ``'W0'-'W6'``  | Weekday (0=Monday)         | Used to compute initial |
374   |                |                            | rollover time           |
375   +----------------+----------------------------+-------------------------+
376   | ``'midnight'`` | Roll over at midnight, if  | Used to compute initial |
377   |                | *atTime* not specified,    | rollover time           |
378   |                | else at time *atTime*      |                         |
379   +----------------+----------------------------+-------------------------+
380
381   When using weekday-based rotation, specify 'W0' for Monday, 'W1' for
382   Tuesday, and so on up to 'W6' for Sunday. In this case, the value passed for
383   *interval* isn't used.
384
385   The system will save old log files by appending extensions to the filename.
386   The extensions are date-and-time based, using the strftime format
387   ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on the
388   rollover interval.
389
390   When computing the next rollover time for the first time (when the handler
391   is created), the last modification time of an existing log file, or else
392   the current time, is used to compute when the next rotation will occur.
393
394   If the *utc* argument is true, times in UTC will be used; otherwise
395   local time is used.
396
397   If *backupCount* is nonzero, at most *backupCount* files
398   will be kept, and if more would be created when rollover occurs, the oldest
399   one is deleted. The deletion logic uses the interval to determine which
400   files to delete, so changing the interval may leave old files lying around.
401
402   If *delay* is true, then file opening is deferred until the first call to
403   :meth:`emit`.
404
405   If *atTime* is not ``None``, it must be a ``datetime.time`` instance which
406   specifies the time of day when rollover occurs, for the cases where rollover
407   is set to happen "at midnight" or "on a particular weekday". Note that in
408   these cases, the *atTime* value is effectively used to compute the *initial*
409   rollover, and subsequent rollovers would be calculated via the normal
410   interval calculation.
411
412   If *errors* is specified, it's used to determine how encoding errors are
413   handled.
414
415   .. note:: Calculation of the initial rollover time is done when the handler
416      is initialised. Calculation of subsequent rollover times is done only
417      when rollover occurs, and rollover occurs only when emitting output. If
418      this is not kept in mind, it might lead to some confusion. For example,
419      if an interval of "every minute" is set, that does not mean you will
420      always see log files with times (in the filename) separated by a minute;
421      if, during application execution, logging output is generated more
422      frequently than once a minute, *then* you can expect to see log files
423      with times separated by a minute. If, on the other hand, logging messages
424      are only output once every five minutes (say), then there will be gaps in
425      the file times corresponding to the minutes where no output (and hence no
426      rollover) occurred.
427
428   .. versionchanged:: 3.4
429      *atTime* parameter was added.
430
431   .. versionchanged:: 3.6
432      As well as string values, :class:`~pathlib.Path` objects are also accepted
433      for the *filename* argument.
434
435   .. versionchanged:: 3.9
436      The *errors* parameter was added.
437
438   .. method:: doRollover()
439
440      Does a rollover, as described above.
441
442   .. method:: emit(record)
443
444      Outputs the record to the file, catering for rollover as described above.
445
446
447.. _socket-handler:
448
449SocketHandler
450^^^^^^^^^^^^^
451
452The :class:`SocketHandler` class, located in the :mod:`logging.handlers` module,
453sends logging output to a network socket. The base class uses a TCP socket.
454
455
456.. class:: SocketHandler(host, port)
457
458   Returns a new instance of the :class:`SocketHandler` class intended to
459   communicate with a remote machine whose address is given by *host* and *port*.
460
461   .. versionchanged:: 3.4
462      If ``port`` is specified as ``None``, a Unix domain socket is created
463      using the value in ``host`` - otherwise, a TCP socket is created.
464
465   .. method:: close()
466
467      Closes the socket.
468
469
470   .. method:: emit()
471
472      Pickles the record's attribute dictionary and writes it to the socket in
473      binary format. If there is an error with the socket, silently drops the
474      packet. If the connection was previously lost, re-establishes the
475      connection. To unpickle the record at the receiving end into a
476      :class:`~logging.LogRecord`, use the :func:`~logging.makeLogRecord`
477      function.
478
479
480   .. method:: handleError()
481
482      Handles an error which has occurred during :meth:`emit`. The most likely
483      cause is a lost connection. Closes the socket so that we can retry on the
484      next event.
485
486
487   .. method:: makeSocket()
488
489      This is a factory method which allows subclasses to define the precise
490      type of socket they want. The default implementation creates a TCP socket
491      (:const:`socket.SOCK_STREAM`).
492
493
494   .. method:: makePickle(record)
495
496      Pickles the record's attribute dictionary in binary format with a length
497      prefix, and returns it ready for transmission across the socket. The
498      details of this operation are equivalent to::
499
500          data = pickle.dumps(record_attr_dict, 1)
501          datalen = struct.pack('>L', len(data))
502          return datalen + data
503
504      Note that pickles aren't completely secure. If you are concerned about
505      security, you may want to override this method to implement a more secure
506      mechanism. For example, you can sign pickles using HMAC and then verify
507      them on the receiving end, or alternatively you can disable unpickling of
508      global objects on the receiving end.
509
510
511   .. method:: send(packet)
512
513      Send a pickled byte-string *packet* to the socket. The format of the sent
514      byte-string is as described in the documentation for
515      :meth:`~SocketHandler.makePickle`.
516
517      This function allows for partial sends, which can happen when the network
518      is busy.
519
520
521   .. method:: createSocket()
522
523      Tries to create a socket; on failure, uses an exponential back-off
524      algorithm.  On initial failure, the handler will drop the message it was
525      trying to send.  When subsequent messages are handled by the same
526      instance, it will not try connecting until some time has passed.  The
527      default parameters are such that the initial delay is one second, and if
528      after that delay the connection still can't be made, the handler will
529      double the delay each time up to a maximum of 30 seconds.
530
531      This behaviour is controlled by the following handler attributes:
532
533      * ``retryStart`` (initial delay, defaulting to 1.0 seconds).
534      * ``retryFactor`` (multiplier, defaulting to 2.0).
535      * ``retryMax`` (maximum delay, defaulting to 30.0 seconds).
536
537      This means that if the remote listener starts up *after* the handler has
538      been used, you could lose messages (since the handler won't even attempt
539      a connection until the delay has elapsed, but just silently drop messages
540      during the delay period).
541
542
543.. _datagram-handler:
544
545DatagramHandler
546^^^^^^^^^^^^^^^
547
548The :class:`DatagramHandler` class, located in the :mod:`logging.handlers`
549module, inherits from :class:`SocketHandler` to support sending logging messages
550over UDP sockets.
551
552
553.. class:: DatagramHandler(host, port)
554
555   Returns a new instance of the :class:`DatagramHandler` class intended to
556   communicate with a remote machine whose address is given by *host* and *port*.
557
558   .. versionchanged:: 3.4
559      If ``port`` is specified as ``None``, a Unix domain socket is created
560      using the value in ``host`` - otherwise, a UDP socket is created.
561
562   .. method:: emit()
563
564      Pickles the record's attribute dictionary and writes it to the socket in
565      binary format. If there is an error with the socket, silently drops the
566      packet. To unpickle the record at the receiving end into a
567      :class:`~logging.LogRecord`, use the :func:`~logging.makeLogRecord`
568      function.
569
570
571   .. method:: makeSocket()
572
573      The factory method of :class:`SocketHandler` is here overridden to create
574      a UDP socket (:const:`socket.SOCK_DGRAM`).
575
576
577   .. method:: send(s)
578
579      Send a pickled byte-string to a socket. The format of the sent byte-string
580      is as described in the documentation for :meth:`SocketHandler.makePickle`.
581
582
583.. _syslog-handler:
584
585SysLogHandler
586^^^^^^^^^^^^^
587
588The :class:`SysLogHandler` class, located in the :mod:`logging.handlers` module,
589supports sending logging messages to a remote or local Unix syslog.
590
591
592.. class:: SysLogHandler(address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER, socktype=socket.SOCK_DGRAM)
593
594   Returns a new instance of the :class:`SysLogHandler` class intended to
595   communicate with a remote Unix machine whose address is given by *address* in
596   the form of a ``(host, port)`` tuple.  If *address* is not specified,
597   ``('localhost', 514)`` is used.  The address is used to open a socket.  An
598   alternative to providing a ``(host, port)`` tuple is providing an address as a
599   string, for example '/dev/log'. In this case, a Unix domain socket is used to
600   send the message to the syslog. If *facility* is not specified,
601   :const:`LOG_USER` is used. The type of socket opened depends on the
602   *socktype* argument, which defaults to :const:`socket.SOCK_DGRAM` and thus
603   opens a UDP socket. To open a TCP socket (for use with the newer syslog
604   daemons such as rsyslog), specify a value of :const:`socket.SOCK_STREAM`.
605
606   Note that if your server is not listening on UDP port 514,
607   :class:`SysLogHandler` may appear not to work. In that case, check what
608   address you should be using for a domain socket - it's system dependent.
609   For example, on Linux it's usually '/dev/log' but on OS/X it's
610   '/var/run/syslog'. You'll need to check your platform and use the
611   appropriate address (you may need to do this check at runtime if your
612   application needs to run on several platforms). On Windows, you pretty
613   much have to use the UDP option.
614
615   .. versionchanged:: 3.2
616      *socktype* was added.
617
618
619   .. method:: close()
620
621      Closes the socket to the remote host.
622
623
624   .. method:: emit(record)
625
626      The record is formatted, and then sent to the syslog server. If exception
627      information is present, it is *not* sent to the server.
628
629      .. versionchanged:: 3.2.1
630         (See: :issue:`12168`.) In earlier versions, the message sent to the
631         syslog daemons was always terminated with a NUL byte, because early
632         versions of these daemons expected a NUL terminated message - even
633         though it's not in the relevant specification (:rfc:`5424`). More recent
634         versions of these daemons don't expect the NUL byte but strip it off
635         if it's there, and even more recent daemons (which adhere more closely
636         to RFC 5424) pass the NUL byte on as part of the message.
637
638         To enable easier handling of syslog messages in the face of all these
639         differing daemon behaviours, the appending of the NUL byte has been
640         made configurable, through the use of a class-level attribute,
641         ``append_nul``. This defaults to ``True`` (preserving the existing
642         behaviour) but can be set to ``False`` on a ``SysLogHandler`` instance
643         in order for that instance to *not* append the NUL terminator.
644
645      .. versionchanged:: 3.3
646         (See: :issue:`12419`.) In earlier versions, there was no facility for
647         an "ident" or "tag" prefix to identify the source of the message. This
648         can now be specified using a class-level attribute, defaulting to
649         ``""`` to preserve existing behaviour, but which can be overridden on
650         a ``SysLogHandler`` instance in order for that instance to prepend
651         the ident to every message handled. Note that the provided ident must
652         be text, not bytes, and is prepended to the message exactly as is.
653
654   .. method:: encodePriority(facility, priority)
655
656      Encodes the facility and priority into an integer. You can pass in strings
657      or integers - if strings are passed, internal mapping dictionaries are
658      used to convert them to integers.
659
660      The symbolic ``LOG_`` values are defined in :class:`SysLogHandler` and
661      mirror the values defined in the ``sys/syslog.h`` header file.
662
663      **Priorities**
664
665      +--------------------------+---------------+
666      | Name (string)            | Symbolic value|
667      +==========================+===============+
668      | ``alert``                | LOG_ALERT     |
669      +--------------------------+---------------+
670      | ``crit`` or ``critical`` | LOG_CRIT      |
671      +--------------------------+---------------+
672      | ``debug``                | LOG_DEBUG     |
673      +--------------------------+---------------+
674      | ``emerg`` or ``panic``   | LOG_EMERG     |
675      +--------------------------+---------------+
676      | ``err`` or ``error``     | LOG_ERR       |
677      +--------------------------+---------------+
678      | ``info``                 | LOG_INFO      |
679      +--------------------------+---------------+
680      | ``notice``               | LOG_NOTICE    |
681      +--------------------------+---------------+
682      | ``warn`` or ``warning``  | LOG_WARNING   |
683      +--------------------------+---------------+
684
685      **Facilities**
686
687      +---------------+---------------+
688      | Name (string) | Symbolic value|
689      +===============+===============+
690      | ``auth``      | LOG_AUTH      |
691      +---------------+---------------+
692      | ``authpriv``  | LOG_AUTHPRIV  |
693      +---------------+---------------+
694      | ``cron``      | LOG_CRON      |
695      +---------------+---------------+
696      | ``daemon``    | LOG_DAEMON    |
697      +---------------+---------------+
698      | ``ftp``       | LOG_FTP       |
699      +---------------+---------------+
700      | ``kern``      | LOG_KERN      |
701      +---------------+---------------+
702      | ``lpr``       | LOG_LPR       |
703      +---------------+---------------+
704      | ``mail``      | LOG_MAIL      |
705      +---------------+---------------+
706      | ``news``      | LOG_NEWS      |
707      +---------------+---------------+
708      | ``syslog``    | LOG_SYSLOG    |
709      +---------------+---------------+
710      | ``user``      | LOG_USER      |
711      +---------------+---------------+
712      | ``uucp``      | LOG_UUCP      |
713      +---------------+---------------+
714      | ``local0``    | LOG_LOCAL0    |
715      +---------------+---------------+
716      | ``local1``    | LOG_LOCAL1    |
717      +---------------+---------------+
718      | ``local2``    | LOG_LOCAL2    |
719      +---------------+---------------+
720      | ``local3``    | LOG_LOCAL3    |
721      +---------------+---------------+
722      | ``local4``    | LOG_LOCAL4    |
723      +---------------+---------------+
724      | ``local5``    | LOG_LOCAL5    |
725      +---------------+---------------+
726      | ``local6``    | LOG_LOCAL6    |
727      +---------------+---------------+
728      | ``local7``    | LOG_LOCAL7    |
729      +---------------+---------------+
730
731   .. method:: mapPriority(levelname)
732
733      Maps a logging level name to a syslog priority name.
734      You may need to override this if you are using custom levels, or
735      if the default algorithm is not suitable for your needs. The
736      default algorithm maps ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and
737      ``CRITICAL`` to the equivalent syslog names, and all other level
738      names to 'warning'.
739
740.. _nt-eventlog-handler:
741
742NTEventLogHandler
743^^^^^^^^^^^^^^^^^
744
745The :class:`NTEventLogHandler` class, located in the :mod:`logging.handlers`
746module, supports sending logging messages to a local Windows NT, Windows 2000 or
747Windows XP event log. Before you can use it, you need Mark Hammond's Win32
748extensions for Python installed.
749
750
751.. class:: NTEventLogHandler(appname, dllname=None, logtype='Application')
752
753   Returns a new instance of the :class:`NTEventLogHandler` class. The *appname* is
754   used to define the application name as it appears in the event log. An
755   appropriate registry entry is created using this name. The *dllname* should give
756   the fully qualified pathname of a .dll or .exe which contains message
757   definitions to hold in the log (if not specified, ``'win32service.pyd'`` is used
758   - this is installed with the Win32 extensions and contains some basic
759   placeholder message definitions. Note that use of these placeholders will make
760   your event logs big, as the entire message source is held in the log. If you
761   want slimmer logs, you have to pass in the name of your own .dll or .exe which
762   contains the message definitions you want to use in the event log). The
763   *logtype* is one of ``'Application'``, ``'System'`` or ``'Security'``, and
764   defaults to ``'Application'``.
765
766
767   .. method:: close()
768
769      At this point, you can remove the application name from the registry as a
770      source of event log entries. However, if you do this, you will not be able
771      to see the events as you intended in the Event Log Viewer - it needs to be
772      able to access the registry to get the .dll name. The current version does
773      not do this.
774
775
776   .. method:: emit(record)
777
778      Determines the message ID, event category and event type, and then logs
779      the message in the NT event log.
780
781
782   .. method:: getEventCategory(record)
783
784      Returns the event category for the record. Override this if you want to
785      specify your own categories. This version returns 0.
786
787
788   .. method:: getEventType(record)
789
790      Returns the event type for the record. Override this if you want to
791      specify your own types. This version does a mapping using the handler's
792      typemap attribute, which is set up in :meth:`__init__` to a dictionary
793      which contains mappings for :const:`DEBUG`, :const:`INFO`,
794      :const:`WARNING`, :const:`ERROR` and :const:`CRITICAL`. If you are using
795      your own levels, you will either need to override this method or place a
796      suitable dictionary in the handler's *typemap* attribute.
797
798
799   .. method:: getMessageID(record)
800
801      Returns the message ID for the record. If you are using your own messages,
802      you could do this by having the *msg* passed to the logger being an ID
803      rather than a format string. Then, in here, you could use a dictionary
804      lookup to get the message ID. This version returns 1, which is the base
805      message ID in :file:`win32service.pyd`.
806
807.. _smtp-handler:
808
809SMTPHandler
810^^^^^^^^^^^
811
812The :class:`SMTPHandler` class, located in the :mod:`logging.handlers` module,
813supports sending logging messages to an email address via SMTP.
814
815
816.. class:: SMTPHandler(mailhost, fromaddr, toaddrs, subject, credentials=None, secure=None, timeout=1.0)
817
818   Returns a new instance of the :class:`SMTPHandler` class. The instance is
819   initialized with the from and to addresses and subject line of the email. The
820   *toaddrs* should be a list of strings. To specify a non-standard SMTP port, use
821   the (host, port) tuple format for the *mailhost* argument. If you use a string,
822   the standard SMTP port is used. If your SMTP server requires authentication, you
823   can specify a (username, password) tuple for the *credentials* argument.
824
825   To specify the use of a secure protocol (TLS), pass in a tuple to the
826   *secure* argument. This will only be used when authentication credentials are
827   supplied. The tuple should be either an empty tuple, or a single-value tuple
828   with the name of a keyfile, or a 2-value tuple with the names of the keyfile
829   and certificate file. (This tuple is passed to the
830   :meth:`smtplib.SMTP.starttls` method.)
831
832   A timeout can be specified for communication with the SMTP server using the
833   *timeout* argument.
834
835   .. versionadded:: 3.3
836      The *timeout* argument was added.
837
838   .. method:: emit(record)
839
840      Formats the record and sends it to the specified addressees.
841
842
843   .. method:: getSubject(record)
844
845      If you want to specify a subject line which is record-dependent, override
846      this method.
847
848.. _memory-handler:
849
850MemoryHandler
851^^^^^^^^^^^^^
852
853The :class:`MemoryHandler` class, located in the :mod:`logging.handlers` module,
854supports buffering of logging records in memory, periodically flushing them to a
855:dfn:`target` handler. Flushing occurs whenever the buffer is full, or when an
856event of a certain severity or greater is seen.
857
858:class:`MemoryHandler` is a subclass of the more general
859:class:`BufferingHandler`, which is an abstract class. This buffers logging
860records in memory. Whenever each record is added to the buffer, a check is made
861by calling :meth:`shouldFlush` to see if the buffer should be flushed.  If it
862should, then :meth:`flush` is expected to do the flushing.
863
864
865.. class:: BufferingHandler(capacity)
866
867   Initializes the handler with a buffer of the specified capacity. Here,
868   *capacity* means the number of logging records buffered.
869
870
871   .. method:: emit(record)
872
873      Append the record to the buffer. If :meth:`shouldFlush` returns true,
874      call :meth:`flush` to process the buffer.
875
876
877   .. method:: flush()
878
879      You can override this to implement custom flushing behavior. This version
880      just zaps the buffer to empty.
881
882
883   .. method:: shouldFlush(record)
884
885      Return ``True`` if the buffer is up to capacity. This method can be
886      overridden to implement custom flushing strategies.
887
888
889.. class:: MemoryHandler(capacity, flushLevel=ERROR, target=None, flushOnClose=True)
890
891   Returns a new instance of the :class:`MemoryHandler` class. The instance is
892   initialized with a buffer size of *capacity* (number of records buffered).
893   If *flushLevel* is not specified, :const:`ERROR` is used. If no *target* is
894   specified, the target will need to be set using :meth:`setTarget` before this
895   handler does anything useful. If *flushOnClose* is specified as ``False``,
896   then the buffer is *not* flushed when the handler is closed. If not specified
897   or specified as ``True``, the previous behaviour of flushing the buffer will
898   occur when the handler is closed.
899
900   .. versionchanged:: 3.6
901      The *flushOnClose* parameter was added.
902
903
904   .. method:: close()
905
906      Calls :meth:`flush`, sets the target to ``None`` and clears the
907      buffer.
908
909
910   .. method:: flush()
911
912      For a :class:`MemoryHandler`, flushing means just sending the buffered
913      records to the target, if there is one. The buffer is also cleared when
914      this happens. Override if you want different behavior.
915
916
917   .. method:: setTarget(target)
918
919      Sets the target handler for this handler.
920
921
922   .. method:: shouldFlush(record)
923
924      Checks for buffer full or a record at the *flushLevel* or higher.
925
926
927.. _http-handler:
928
929HTTPHandler
930^^^^^^^^^^^
931
932The :class:`HTTPHandler` class, located in the :mod:`logging.handlers` module,
933supports sending logging messages to a web server, using either ``GET`` or
934``POST`` semantics.
935
936
937.. class:: HTTPHandler(host, url, method='GET', secure=False, credentials=None, context=None)
938
939   Returns a new instance of the :class:`HTTPHandler` class. The *host* can be
940   of the form ``host:port``, should you need to use a specific port number.  If
941   no *method* is specified, ``GET`` is used. If *secure* is true, a HTTPS
942   connection will be used. The *context* parameter may be set to a
943   :class:`ssl.SSLContext` instance to configure the SSL settings used for the
944   HTTPS connection. If *credentials* is specified, it should be a 2-tuple
945   consisting of userid and password, which will be placed in a HTTP
946   'Authorization' header using Basic authentication. If you specify
947   credentials, you should also specify secure=True so that your userid and
948   password are not passed in cleartext across the wire.
949
950   .. versionchanged:: 3.5
951      The *context* parameter was added.
952
953   .. method:: mapLogRecord(record)
954
955      Provides a dictionary, based on ``record``, which is to be URL-encoded
956      and sent to the web server. The default implementation just returns
957      ``record.__dict__``. This method can be overridden if e.g. only a
958      subset of :class:`~logging.LogRecord` is to be sent to the web server, or
959      if more specific customization of what's sent to the server is required.
960
961   .. method:: emit(record)
962
963      Sends the record to the web server as a URL-encoded dictionary. The
964      :meth:`mapLogRecord` method is used to convert the record to the
965      dictionary to be sent.
966
967   .. note:: Since preparing a record for sending it to a web server is not
968      the same as a generic formatting operation, using
969      :meth:`~logging.Handler.setFormatter` to specify a
970      :class:`~logging.Formatter` for a :class:`HTTPHandler` has no effect.
971      Instead of calling :meth:`~logging.Handler.format`, this handler calls
972      :meth:`mapLogRecord` and then :func:`urllib.parse.urlencode` to encode the
973      dictionary in a form suitable for sending to a web server.
974
975
976.. _queue-handler:
977
978
979QueueHandler
980^^^^^^^^^^^^
981
982.. versionadded:: 3.2
983
984The :class:`QueueHandler` class, located in the :mod:`logging.handlers` module,
985supports sending logging messages to a queue, such as those implemented in the
986:mod:`queue` or :mod:`multiprocessing` modules.
987
988Along with the :class:`QueueListener` class, :class:`QueueHandler` can be used
989to let handlers do their work on a separate thread from the one which does the
990logging. This is important in web applications and also other service
991applications where threads servicing clients need to respond as quickly as
992possible, while any potentially slow operations (such as sending an email via
993:class:`SMTPHandler`) are done on a separate thread.
994
995.. class:: QueueHandler(queue)
996
997   Returns a new instance of the :class:`QueueHandler` class. The instance is
998   initialized with the queue to send messages to. The *queue* can be any
999   queue-like object; it's used as-is by the :meth:`enqueue` method, which
1000   needs to know how to send messages to it. The queue is not *required* to
1001   have the task tracking API, which means that you can use
1002   :class:`~queue.SimpleQueue` instances for *queue*.
1003
1004
1005   .. method:: emit(record)
1006
1007      Enqueues the result of preparing the LogRecord. Should an exception
1008      occur (e.g. because a bounded queue has filled up), the
1009      :meth:`~logging.Handler.handleError` method is called to handle the
1010      error. This can result in the record silently being dropped (if
1011      :attr:`logging.raiseExceptions` is ``False``) or a message printed to
1012      ``sys.stderr`` (if :attr:`logging.raiseExceptions` is ``True``).
1013
1014   .. method:: prepare(record)
1015
1016      Prepares a record for queuing. The object returned by this
1017      method is enqueued.
1018
1019      The base implementation formats the record to merge the message,
1020      arguments, and exception information, if present.  It also removes
1021      unpickleable items from the record in-place. Specifically, it overwrites
1022      the record's :attr:`msg` and :attr:`message` attributes with the merged
1023      message (obtained by calling the handler's :meth:`format` method), and
1024      sets the :attr:`args`, :attr:`exc_info` and :attr:`exc_text` attributes
1025      to ``None``.
1026
1027      You might want to override this method if you want to convert
1028      the record to a dict or JSON string, or send a modified copy
1029      of the record while leaving the original intact.
1030
1031   .. method:: enqueue(record)
1032
1033      Enqueues the record on the queue using ``put_nowait()``; you may
1034      want to override this if you want to use blocking behaviour, or a
1035      timeout, or a customized queue implementation.
1036
1037
1038
1039.. _queue-listener:
1040
1041QueueListener
1042^^^^^^^^^^^^^
1043
1044.. versionadded:: 3.2
1045
1046The :class:`QueueListener` class, located in the :mod:`logging.handlers`
1047module, supports receiving logging messages from a queue, such as those
1048implemented in the :mod:`queue` or :mod:`multiprocessing` modules. The
1049messages are received from a queue in an internal thread and passed, on
1050the same thread, to one or more handlers for processing. While
1051:class:`QueueListener` is not itself a handler, it is documented here
1052because it works hand-in-hand with :class:`QueueHandler`.
1053
1054Along with the :class:`QueueHandler` class, :class:`QueueListener` can be used
1055to let handlers do their work on a separate thread from the one which does the
1056logging. This is important in web applications and also other service
1057applications where threads servicing clients need to respond as quickly as
1058possible, while any potentially slow operations (such as sending an email via
1059:class:`SMTPHandler`) are done on a separate thread.
1060
1061.. class:: QueueListener(queue, *handlers, respect_handler_level=False)
1062
1063   Returns a new instance of the :class:`QueueListener` class. The instance is
1064   initialized with the queue to send messages to and a list of handlers which
1065   will handle entries placed on the queue. The queue can be any queue-like
1066   object; it's passed as-is to the :meth:`dequeue` method, which needs
1067   to know how to get messages from it. The queue is not *required* to have the
1068   task tracking API (though it's used if available), which means that you can
1069   use :class:`~queue.SimpleQueue` instances for *queue*.
1070
1071   If ``respect_handler_level`` is ``True``, a handler's level is respected
1072   (compared with the level for the message) when deciding whether to pass
1073   messages to that handler; otherwise, the behaviour is as in previous Python
1074   versions - to always pass each message to each handler.
1075
1076   .. versionchanged:: 3.5
1077      The ``respect_handler_level`` argument was added.
1078
1079   .. method:: dequeue(block)
1080
1081      Dequeues a record and return it, optionally blocking.
1082
1083      The base implementation uses ``get()``. You may want to override this
1084      method if you want to use timeouts or work with custom queue
1085      implementations.
1086
1087   .. method:: prepare(record)
1088
1089      Prepare a record for handling.
1090
1091      This implementation just returns the passed-in record. You may want to
1092      override this method if you need to do any custom marshalling or
1093      manipulation of the record before passing it to the handlers.
1094
1095   .. method:: handle(record)
1096
1097      Handle a record.
1098
1099      This just loops through the handlers offering them the record
1100      to handle. The actual object passed to the handlers is that which
1101      is returned from :meth:`prepare`.
1102
1103   .. method:: start()
1104
1105      Starts the listener.
1106
1107      This starts up a background thread to monitor the queue for
1108      LogRecords to process.
1109
1110   .. method:: stop()
1111
1112      Stops the listener.
1113
1114      This asks the thread to terminate, and then waits for it to do so.
1115      Note that if you don't call this before your application exits, there
1116      may be some records still left on the queue, which won't be processed.
1117
1118   .. method:: enqueue_sentinel()
1119
1120      Writes a sentinel to the queue to tell the listener to quit. This
1121      implementation uses ``put_nowait()``.  You may want to override this
1122      method if you want to use timeouts or work with custom queue
1123      implementations.
1124
1125      .. versionadded:: 3.3
1126
1127
1128.. seealso::
1129
1130   Module :mod:`logging`
1131      API reference for the logging module.
1132
1133   Module :mod:`logging.config`
1134      Configuration API for the logging module.
1135
1136
1137