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