blob: 0d3928c352643ae5c6dce09dbc369db78c43d7d3 [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
171
Vinay Sajipc63619b2010-12-19 12:56:57 +0000172 .. method:: emit(record)
173
Vinay Sajip29a14452015-10-01 20:54:41 +0100174 Outputs the record to the file, but first calls :meth:`reopenIfNeeded` to
175 reopen the file if it has changed.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000176
Vinay Sajip23b94d02012-01-04 12:02:26 +0000177.. _base-rotating-handler:
178
179BaseRotatingHandler
180^^^^^^^^^^^^^^^^^^^
181
182The :class:`BaseRotatingHandler` class, located in the :mod:`logging.handlers`
183module, is the base class for the rotating file handlers,
184:class:`RotatingFileHandler` and :class:`TimedRotatingFileHandler`. You should
185not need to instantiate this class, but it has attributes and methods you may
186need to override.
187
188.. class:: BaseRotatingHandler(filename, mode, encoding=None, delay=False)
189
190 The parameters are as for :class:`FileHandler`. The attributes are:
191
192 .. attribute:: namer
193
194 If this attribute is set to a callable, the :meth:`rotation_filename`
195 method delegates to this callable. The parameters passed to the callable
196 are those passed to :meth:`rotation_filename`.
197
198 .. note:: The namer function is called quite a few times during rollover,
199 so it should be as simple and as fast as possible. It should also
200 return the same output every time for a given input, otherwise the
201 rollover behaviour may not work as expected.
202
203 .. versionadded:: 3.3
204
205
206 .. attribute:: BaseRotatingHandler.rotator
207
208 If this attribute is set to a callable, the :meth:`rotate` method
209 delegates to this callable. The parameters passed to the callable are
210 those passed to :meth:`rotate`.
211
212 .. versionadded:: 3.3
213
214 .. method:: BaseRotatingHandler.rotation_filename(default_name)
215
216 Modify the filename of a log file when rotating.
217
218 This is provided so that a custom filename can be provided.
219
220 The default implementation calls the 'namer' attribute of the handler,
221 if it's callable, passing the default name to it. If the attribute isn't
Ezio Melotti226231c2012-01-18 05:40:00 +0200222 callable (the default is ``None``), the name is returned unchanged.
Vinay Sajip23b94d02012-01-04 12:02:26 +0000223
224 :param default_name: The default name for the log file.
225
226 .. versionadded:: 3.3
227
228
229 .. method:: BaseRotatingHandler.rotate(source, dest)
230
231 When rotating, rotate the current log.
232
233 The default implementation calls the 'rotator' attribute of the handler,
234 if it's callable, passing the source and dest arguments to it. If the
Ezio Melotti226231c2012-01-18 05:40:00 +0200235 attribute isn't callable (the default is ``None``), the source is simply
Vinay Sajip23b94d02012-01-04 12:02:26 +0000236 renamed to the destination.
237
238 :param source: The source filename. This is normally the base
239 filename, e.g. 'test.log'
240 :param dest: The destination filename. This is normally
241 what the source is rotated to, e.g. 'test.log.1'.
242
243 .. versionadded:: 3.3
244
245The reason the attributes exist is to save you having to subclass - you can use
246the same callables for instances of :class:`RotatingFileHandler` and
247:class:`TimedRotatingFileHandler`. If either the namer or rotator callable
248raises an exception, this will be handled in the same way as any other
249exception during an :meth:`emit` call, i.e. via the :meth:`handleError` method
250of the handler.
251
252If you need to make more significant changes to rotation processing, you can
253override the methods.
254
255For an example, see :ref:`cookbook-rotator-namer`.
256
257
Vinay Sajipc63619b2010-12-19 12:56:57 +0000258.. _rotating-file-handler:
259
260RotatingFileHandler
261^^^^^^^^^^^^^^^^^^^
262
263The :class:`RotatingFileHandler` class, located in the :mod:`logging.handlers`
264module, supports rotation of disk log files.
265
266
267.. class:: RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0)
268
269 Returns a new instance of the :class:`RotatingFileHandler` class. The specified
270 file is opened and used as the stream for logging. If *mode* is not specified,
271 ``'a'`` is used. If *encoding* is not *None*, it is used to open the file
272 with that encoding. If *delay* is true, then file opening is deferred until the
273 first call to :meth:`emit`. By default, the file grows indefinitely.
274
275 You can use the *maxBytes* and *backupCount* values to allow the file to
276 :dfn:`rollover` at a predetermined size. When the size is about to be exceeded,
277 the file is closed and a new file is silently opened for output. Rollover occurs
Vinay Sajipff37cfe2015-01-23 21:19:04 +0000278 whenever the current log file is nearly *maxBytes* in length; if either of
279 *maxBytes* or *backupCount* is zero, rollover never occurs. If *backupCount*
280 is non-zero, the system will save old log files by appending the extensions
281 '.1', '.2' etc., to the filename. For example, with a *backupCount* of 5 and
282 a base file name of :file:`app.log`, you would get :file:`app.log`,
283 :file:`app.log.1`, :file:`app.log.2`, up to :file:`app.log.5`. The file being
284 written to is always :file:`app.log`. When this file is filled, it is closed
285 and renamed to :file:`app.log.1`, and if files :file:`app.log.1`,
286 :file:`app.log.2`, etc. exist, then they are renamed to :file:`app.log.2`,
287 :file:`app.log.3` etc. respectively.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000288
289
290 .. method:: doRollover()
291
292 Does a rollover, as described above.
293
294
295 .. method:: emit(record)
296
297 Outputs the record to the file, catering for rollover as described
298 previously.
299
300.. _timed-rotating-file-handler:
301
302TimedRotatingFileHandler
303^^^^^^^^^^^^^^^^^^^^^^^^
304
305The :class:`TimedRotatingFileHandler` class, located in the
306:mod:`logging.handlers` module, supports rotation of disk log files at certain
307timed intervals.
308
309
Vinay Sajipa7130792013-04-12 17:04:23 +0100310.. class:: TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False, atTime=None)
Vinay Sajipc63619b2010-12-19 12:56:57 +0000311
312 Returns a new instance of the :class:`TimedRotatingFileHandler` class. The
313 specified file is opened and used as the stream for logging. On rotating it also
314 sets the filename suffix. Rotating happens based on the product of *when* and
315 *interval*.
316
317 You can use the *when* to specify the type of *interval*. The list of possible
318 values is below. Note that they are not case sensitive.
319
320 +----------------+-----------------------+
321 | Value | Type of interval |
322 +================+=======================+
323 | ``'S'`` | Seconds |
324 +----------------+-----------------------+
325 | ``'M'`` | Minutes |
326 +----------------+-----------------------+
327 | ``'H'`` | Hours |
328 +----------------+-----------------------+
329 | ``'D'`` | Days |
330 +----------------+-----------------------+
Vinay Sajip832d99b2013-03-08 23:24:30 +0000331 | ``'W0'-'W6'`` | Weekday (0=Monday) |
Vinay Sajipc63619b2010-12-19 12:56:57 +0000332 +----------------+-----------------------+
333 | ``'midnight'`` | Roll over at midnight |
334 +----------------+-----------------------+
335
Vinay Sajip832d99b2013-03-08 23:24:30 +0000336 When using weekday-based rotation, specify 'W0' for Monday, 'W1' for
337 Tuesday, and so on up to 'W6' for Sunday. In this case, the value passed for
338 *interval* isn't used.
339
Vinay Sajipc63619b2010-12-19 12:56:57 +0000340 The system will save old log files by appending extensions to the filename.
341 The extensions are date-and-time based, using the strftime format
342 ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on the
343 rollover interval.
344
345 When computing the next rollover time for the first time (when the handler
346 is created), the last modification time of an existing log file, or else
347 the current time, is used to compute when the next rotation will occur.
348
349 If the *utc* argument is true, times in UTC will be used; otherwise
350 local time is used.
351
352 If *backupCount* is nonzero, at most *backupCount* files
353 will be kept, and if more would be created when rollover occurs, the oldest
354 one is deleted. The deletion logic uses the interval to determine which
355 files to delete, so changing the interval may leave old files lying around.
356
357 If *delay* is true, then file opening is deferred until the first call to
358 :meth:`emit`.
359
Vinay Sajipa7130792013-04-12 17:04:23 +0100360 If *atTime* is not ``None``, it must be a ``datetime.time`` instance which
361 specifies the time of day when rollover occurs, for the cases where rollover
362 is set to happen "at midnight" or "on a particular weekday".
363
364 .. versionchanged:: 3.4
365 *atTime* parameter was added.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000366
367 .. method:: doRollover()
368
369 Does a rollover, as described above.
370
371
372 .. method:: emit(record)
373
374 Outputs the record to the file, catering for rollover as described above.
375
376
377.. _socket-handler:
378
379SocketHandler
380^^^^^^^^^^^^^
381
382The :class:`SocketHandler` class, located in the :mod:`logging.handlers` module,
383sends logging output to a network socket. The base class uses a TCP socket.
384
385
386.. class:: SocketHandler(host, port)
387
388 Returns a new instance of the :class:`SocketHandler` class intended to
389 communicate with a remote machine whose address is given by *host* and *port*.
390
Vinay Sajip5421f352013-09-27 18:18:28 +0100391 .. versionchanged:: 3.4
392 If ``port`` is specified as ``None``, a Unix domain socket is created
393 using the value in ``host`` - otherwise, a TCP socket is created.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000394
395 .. method:: close()
396
397 Closes the socket.
398
399
400 .. method:: emit()
401
402 Pickles the record's attribute dictionary and writes it to the socket in
403 binary format. If there is an error with the socket, silently drops the
404 packet. If the connection was previously lost, re-establishes the
405 connection. To unpickle the record at the receiving end into a
Vinay Sajip67f39772013-08-17 00:39:42 +0100406 :class:`~logging.LogRecord`, use the :func:`~logging.makeLogRecord`
407 function.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000408
409
410 .. method:: handleError()
411
412 Handles an error which has occurred during :meth:`emit`. The most likely
413 cause is a lost connection. Closes the socket so that we can retry on the
414 next event.
415
416
417 .. method:: makeSocket()
418
419 This is a factory method which allows subclasses to define the precise
420 type of socket they want. The default implementation creates a TCP socket
421 (:const:`socket.SOCK_STREAM`).
422
423
424 .. method:: makePickle(record)
425
426 Pickles the record's attribute dictionary in binary format with a length
427 prefix, and returns it ready for transmission across the socket.
428
429 Note that pickles aren't completely secure. If you are concerned about
430 security, you may want to override this method to implement a more secure
431 mechanism. For example, you can sign pickles using HMAC and then verify
432 them on the receiving end, or alternatively you can disable unpickling of
433 global objects on the receiving end.
434
Georg Brandl08e278a2011-02-15 12:44:43 +0000435
Vinay Sajipc63619b2010-12-19 12:56:57 +0000436 .. method:: send(packet)
437
438 Send a pickled string *packet* to the socket. This function allows for
439 partial sends which can happen when the network is busy.
440
Georg Brandl08e278a2011-02-15 12:44:43 +0000441
Georg Brandldbb95852011-02-15 12:41:17 +0000442 .. method:: createSocket()
443
444 Tries to create a socket; on failure, uses an exponential back-off
Donald Stufft8b852f12014-05-20 12:58:38 -0400445 algorithm. On initial failure, the handler will drop the message it was
Georg Brandldbb95852011-02-15 12:41:17 +0000446 trying to send. When subsequent messages are handled by the same
447 instance, it will not try connecting until some time has passed. The
448 default parameters are such that the initial delay is one second, and if
449 after that delay the connection still can't be made, the handler will
450 double the delay each time up to a maximum of 30 seconds.
451
452 This behaviour is controlled by the following handler attributes:
453
454 * ``retryStart`` (initial delay, defaulting to 1.0 seconds).
455 * ``retryFactor`` (multiplier, defaulting to 2.0).
456 * ``retryMax`` (maximum delay, defaulting to 30.0 seconds).
457
458 This means that if the remote listener starts up *after* the handler has
459 been used, you could lose messages (since the handler won't even attempt
460 a connection until the delay has elapsed, but just silently drop messages
461 during the delay period).
Georg Brandl08e278a2011-02-15 12:44:43 +0000462
Vinay Sajipc63619b2010-12-19 12:56:57 +0000463
464.. _datagram-handler:
465
466DatagramHandler
467^^^^^^^^^^^^^^^
468
469The :class:`DatagramHandler` class, located in the :mod:`logging.handlers`
470module, inherits from :class:`SocketHandler` to support sending logging messages
471over UDP sockets.
472
473
474.. class:: DatagramHandler(host, port)
475
476 Returns a new instance of the :class:`DatagramHandler` class intended to
477 communicate with a remote machine whose address is given by *host* and *port*.
478
Vinay Sajip5421f352013-09-27 18:18:28 +0100479 .. versionchanged:: 3.4
480 If ``port`` is specified as ``None``, a Unix domain socket is created
481 using the value in ``host`` - otherwise, a TCP socket is created.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000482
483 .. method:: emit()
484
485 Pickles the record's attribute dictionary and writes it to the socket in
486 binary format. If there is an error with the socket, silently drops the
487 packet. To unpickle the record at the receiving end into a
Vinay Sajip67f39772013-08-17 00:39:42 +0100488 :class:`~logging.LogRecord`, use the :func:`~logging.makeLogRecord`
489 function.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000490
491
492 .. method:: makeSocket()
493
494 The factory method of :class:`SocketHandler` is here overridden to create
495 a UDP socket (:const:`socket.SOCK_DGRAM`).
496
497
498 .. method:: send(s)
499
500 Send a pickled string to a socket.
501
502
503.. _syslog-handler:
504
505SysLogHandler
506^^^^^^^^^^^^^
507
508The :class:`SysLogHandler` class, located in the :mod:`logging.handlers` module,
509supports sending logging messages to a remote or local Unix syslog.
510
511
512.. class:: SysLogHandler(address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER, socktype=socket.SOCK_DGRAM)
513
514 Returns a new instance of the :class:`SysLogHandler` class intended to
515 communicate with a remote Unix machine whose address is given by *address* in
516 the form of a ``(host, port)`` tuple. If *address* is not specified,
517 ``('localhost', 514)`` is used. The address is used to open a socket. An
518 alternative to providing a ``(host, port)`` tuple is providing an address as a
519 string, for example '/dev/log'. In this case, a Unix domain socket is used to
520 send the message to the syslog. If *facility* is not specified,
521 :const:`LOG_USER` is used. The type of socket opened depends on the
522 *socktype* argument, which defaults to :const:`socket.SOCK_DGRAM` and thus
523 opens a UDP socket. To open a TCP socket (for use with the newer syslog
524 daemons such as rsyslog), specify a value of :const:`socket.SOCK_STREAM`.
525
526 Note that if your server is not listening on UDP port 514,
527 :class:`SysLogHandler` may appear not to work. In that case, check what
528 address you should be using for a domain socket - it's system dependent.
529 For example, on Linux it's usually '/dev/log' but on OS/X it's
530 '/var/run/syslog'. You'll need to check your platform and use the
531 appropriate address (you may need to do this check at runtime if your
532 application needs to run on several platforms). On Windows, you pretty
533 much have to use the UDP option.
534
535 .. versionchanged:: 3.2
536 *socktype* was added.
537
538
539 .. method:: close()
540
541 Closes the socket to the remote host.
542
543
544 .. method:: emit(record)
545
546 The record is formatted, and then sent to the syslog server. If exception
547 information is present, it is *not* sent to the server.
548
Vinay Sajip645e4582011-06-10 18:52:50 +0100549 .. versionchanged:: 3.2.1
550 (See: :issue:`12168`.) In earlier versions, the message sent to the
551 syslog daemons was always terminated with a NUL byte, because early
552 versions of these daemons expected a NUL terminated message - even
553 though it's not in the relevant specification (RF 5424). More recent
554 versions of these daemons don't expect the NUL byte but strip it off
555 if it's there, and even more recent daemons (which adhere more closely
556 to RFC 5424) pass the NUL byte on as part of the message.
557
558 To enable easier handling of syslog messages in the face of all these
559 differing daemon behaviours, the appending of the NUL byte has been
560 made configurable, through the use of a class-level attribute,
561 ``append_nul``. This defaults to ``True`` (preserving the existing
562 behaviour) but can be set to ``False`` on a ``SysLogHandler`` instance
563 in order for that instance to *not* append the NUL terminator.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000564
Vinay Sajip2353e352011-06-27 15:40:06 +0100565 .. versionchanged:: 3.3
566 (See: :issue:`12419`.) In earlier versions, there was no facility for
567 an "ident" or "tag" prefix to identify the source of the message. This
568 can now be specified using a class-level attribute, defaulting to
569 ``""`` to preserve existing behaviour, but which can be overridden on
570 a ``SysLogHandler`` instance in order for that instance to prepend
571 the ident to every message handled. Note that the provided ident must
572 be text, not bytes, and is prepended to the message exactly as is.
573
Vinay Sajipc63619b2010-12-19 12:56:57 +0000574 .. method:: encodePriority(facility, priority)
575
576 Encodes the facility and priority into an integer. You can pass in strings
577 or integers - if strings are passed, internal mapping dictionaries are
578 used to convert them to integers.
579
580 The symbolic ``LOG_`` values are defined in :class:`SysLogHandler` and
581 mirror the values defined in the ``sys/syslog.h`` header file.
582
583 **Priorities**
584
585 +--------------------------+---------------+
586 | Name (string) | Symbolic value|
587 +==========================+===============+
588 | ``alert`` | LOG_ALERT |
589 +--------------------------+---------------+
590 | ``crit`` or ``critical`` | LOG_CRIT |
591 +--------------------------+---------------+
592 | ``debug`` | LOG_DEBUG |
593 +--------------------------+---------------+
594 | ``emerg`` or ``panic`` | LOG_EMERG |
595 +--------------------------+---------------+
596 | ``err`` or ``error`` | LOG_ERR |
597 +--------------------------+---------------+
598 | ``info`` | LOG_INFO |
599 +--------------------------+---------------+
600 | ``notice`` | LOG_NOTICE |
601 +--------------------------+---------------+
602 | ``warn`` or ``warning`` | LOG_WARNING |
603 +--------------------------+---------------+
604
605 **Facilities**
606
607 +---------------+---------------+
608 | Name (string) | Symbolic value|
609 +===============+===============+
610 | ``auth`` | LOG_AUTH |
611 +---------------+---------------+
612 | ``authpriv`` | LOG_AUTHPRIV |
613 +---------------+---------------+
614 | ``cron`` | LOG_CRON |
615 +---------------+---------------+
616 | ``daemon`` | LOG_DAEMON |
617 +---------------+---------------+
618 | ``ftp`` | LOG_FTP |
619 +---------------+---------------+
620 | ``kern`` | LOG_KERN |
621 +---------------+---------------+
622 | ``lpr`` | LOG_LPR |
623 +---------------+---------------+
624 | ``mail`` | LOG_MAIL |
625 +---------------+---------------+
626 | ``news`` | LOG_NEWS |
627 +---------------+---------------+
628 | ``syslog`` | LOG_SYSLOG |
629 +---------------+---------------+
630 | ``user`` | LOG_USER |
631 +---------------+---------------+
632 | ``uucp`` | LOG_UUCP |
633 +---------------+---------------+
634 | ``local0`` | LOG_LOCAL0 |
635 +---------------+---------------+
636 | ``local1`` | LOG_LOCAL1 |
637 +---------------+---------------+
638 | ``local2`` | LOG_LOCAL2 |
639 +---------------+---------------+
640 | ``local3`` | LOG_LOCAL3 |
641 +---------------+---------------+
642 | ``local4`` | LOG_LOCAL4 |
643 +---------------+---------------+
644 | ``local5`` | LOG_LOCAL5 |
645 +---------------+---------------+
646 | ``local6`` | LOG_LOCAL6 |
647 +---------------+---------------+
648 | ``local7`` | LOG_LOCAL7 |
649 +---------------+---------------+
650
651 .. method:: mapPriority(levelname)
652
653 Maps a logging level name to a syslog priority name.
654 You may need to override this if you are using custom levels, or
655 if the default algorithm is not suitable for your needs. The
656 default algorithm maps ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and
657 ``CRITICAL`` to the equivalent syslog names, and all other level
658 names to 'warning'.
659
660.. _nt-eventlog-handler:
661
662NTEventLogHandler
663^^^^^^^^^^^^^^^^^
664
665The :class:`NTEventLogHandler` class, located in the :mod:`logging.handlers`
666module, supports sending logging messages to a local Windows NT, Windows 2000 or
667Windows XP event log. Before you can use it, you need Mark Hammond's Win32
668extensions for Python installed.
669
670
671.. class:: NTEventLogHandler(appname, dllname=None, logtype='Application')
672
673 Returns a new instance of the :class:`NTEventLogHandler` class. The *appname* is
674 used to define the application name as it appears in the event log. An
675 appropriate registry entry is created using this name. The *dllname* should give
676 the fully qualified pathname of a .dll or .exe which contains message
677 definitions to hold in the log (if not specified, ``'win32service.pyd'`` is used
678 - this is installed with the Win32 extensions and contains some basic
679 placeholder message definitions. Note that use of these placeholders will make
680 your event logs big, as the entire message source is held in the log. If you
681 want slimmer logs, you have to pass in the name of your own .dll or .exe which
682 contains the message definitions you want to use in the event log). The
683 *logtype* is one of ``'Application'``, ``'System'`` or ``'Security'``, and
684 defaults to ``'Application'``.
685
686
687 .. method:: close()
688
689 At this point, you can remove the application name from the registry as a
690 source of event log entries. However, if you do this, you will not be able
691 to see the events as you intended in the Event Log Viewer - it needs to be
692 able to access the registry to get the .dll name. The current version does
693 not do this.
694
695
696 .. method:: emit(record)
697
698 Determines the message ID, event category and event type, and then logs
699 the message in the NT event log.
700
701
702 .. method:: getEventCategory(record)
703
704 Returns the event category for the record. Override this if you want to
705 specify your own categories. This version returns 0.
706
707
708 .. method:: getEventType(record)
709
710 Returns the event type for the record. Override this if you want to
711 specify your own types. This version does a mapping using the handler's
712 typemap attribute, which is set up in :meth:`__init__` to a dictionary
713 which contains mappings for :const:`DEBUG`, :const:`INFO`,
714 :const:`WARNING`, :const:`ERROR` and :const:`CRITICAL`. If you are using
715 your own levels, you will either need to override this method or place a
716 suitable dictionary in the handler's *typemap* attribute.
717
718
719 .. method:: getMessageID(record)
720
721 Returns the message ID for the record. If you are using your own messages,
722 you could do this by having the *msg* passed to the logger being an ID
723 rather than a format string. Then, in here, you could use a dictionary
724 lookup to get the message ID. This version returns 1, which is the base
725 message ID in :file:`win32service.pyd`.
726
727.. _smtp-handler:
728
729SMTPHandler
730^^^^^^^^^^^
731
732The :class:`SMTPHandler` class, located in the :mod:`logging.handlers` module,
733supports sending logging messages to an email address via SMTP.
734
735
Vinay Sajip38a12af2012-03-26 17:17:39 +0100736.. class:: SMTPHandler(mailhost, fromaddr, toaddrs, subject, credentials=None, secure=None, timeout=1.0)
Vinay Sajipc63619b2010-12-19 12:56:57 +0000737
738 Returns a new instance of the :class:`SMTPHandler` class. The instance is
739 initialized with the from and to addresses and subject line of the email. The
740 *toaddrs* should be a list of strings. To specify a non-standard SMTP port, use
741 the (host, port) tuple format for the *mailhost* argument. If you use a string,
742 the standard SMTP port is used. If your SMTP server requires authentication, you
743 can specify a (username, password) tuple for the *credentials* argument.
744
Vinay Sajip95259562011-08-01 11:31:52 +0100745 To specify the use of a secure protocol (TLS), pass in a tuple to the
746 *secure* argument. This will only be used when authentication credentials are
747 supplied. The tuple should be either an empty tuple, or a single-value tuple
748 with the name of a keyfile, or a 2-value tuple with the names of the keyfile
749 and certificate file. (This tuple is passed to the
750 :meth:`smtplib.SMTP.starttls` method.)
Vinay Sajipc63619b2010-12-19 12:56:57 +0000751
Vinay Sajip38a12af2012-03-26 17:17:39 +0100752 A timeout can be specified for communication with the SMTP server using the
753 *timeout* argument.
754
755 .. versionadded:: 3.3
756 The *timeout* argument was added.
757
Vinay Sajipc63619b2010-12-19 12:56:57 +0000758 .. method:: emit(record)
759
760 Formats the record and sends it to the specified addressees.
761
762
763 .. method:: getSubject(record)
764
765 If you want to specify a subject line which is record-dependent, override
766 this method.
767
768.. _memory-handler:
769
770MemoryHandler
771^^^^^^^^^^^^^
772
773The :class:`MemoryHandler` class, located in the :mod:`logging.handlers` module,
774supports buffering of logging records in memory, periodically flushing them to a
775:dfn:`target` handler. Flushing occurs whenever the buffer is full, or when an
776event of a certain severity or greater is seen.
777
778:class:`MemoryHandler` is a subclass of the more general
779:class:`BufferingHandler`, which is an abstract class. This buffers logging
780records in memory. Whenever each record is added to the buffer, a check is made
781by calling :meth:`shouldFlush` to see if the buffer should be flushed. If it
Vinay Sajip8ece80f2012-03-26 17:09:58 +0100782should, then :meth:`flush` is expected to do the flushing.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000783
784
785.. class:: BufferingHandler(capacity)
786
787 Initializes the handler with a buffer of the specified capacity.
788
789
790 .. method:: emit(record)
791
792 Appends the record to the buffer. If :meth:`shouldFlush` returns true,
793 calls :meth:`flush` to process the buffer.
794
795
796 .. method:: flush()
797
798 You can override this to implement custom flushing behavior. This version
799 just zaps the buffer to empty.
800
801
802 .. method:: shouldFlush(record)
803
804 Returns true if the buffer is up to capacity. This method can be
805 overridden to implement custom flushing strategies.
806
807
808.. class:: MemoryHandler(capacity, flushLevel=ERROR, target=None)
809
810 Returns a new instance of the :class:`MemoryHandler` class. The instance is
811 initialized with a buffer size of *capacity*. If *flushLevel* is not specified,
812 :const:`ERROR` is used. If no *target* is specified, the target will need to be
813 set using :meth:`setTarget` before this handler does anything useful.
814
815
816 .. method:: close()
817
Ezio Melotti226231c2012-01-18 05:40:00 +0200818 Calls :meth:`flush`, sets the target to ``None`` and clears the
Vinay Sajipc63619b2010-12-19 12:56:57 +0000819 buffer.
820
821
822 .. method:: flush()
823
824 For a :class:`MemoryHandler`, flushing means just sending the buffered
825 records to the target, if there is one. The buffer is also cleared when
826 this happens. Override if you want different behavior.
827
828
829 .. method:: setTarget(target)
830
831 Sets the target handler for this handler.
832
833
834 .. method:: shouldFlush(record)
835
836 Checks for buffer full or a record at the *flushLevel* or higher.
837
838
839.. _http-handler:
840
841HTTPHandler
842^^^^^^^^^^^
843
844The :class:`HTTPHandler` class, located in the :mod:`logging.handlers` module,
845supports sending logging messages to a Web server, using either ``GET`` or
846``POST`` semantics.
847
848
Benjamin Peterson43052a12014-11-23 20:36:44 -0600849.. class:: HTTPHandler(host, url, method='GET', secure=False, credentials=None, context=None)
Vinay Sajipc63619b2010-12-19 12:56:57 +0000850
851 Returns a new instance of the :class:`HTTPHandler` class. The *host* can be
Benjamin Peterson43052a12014-11-23 20:36:44 -0600852 of the form ``host:port``, should you need to use a specific port number. If
853 no *method* is specified, ``GET`` is used. If *secure* is true, a HTTPS
854 connection will be used. The *context* parameter may be set to a
855 :class:`ssl.SSLContext` instance to configure the SSL settings used for the
856 HTTPS connection. If *credentials* is specified, it should be a 2-tuple
857 consisting of userid and password, which will be placed in a HTTP
Vinay Sajipc63619b2010-12-19 12:56:57 +0000858 'Authorization' header using Basic authentication. If you specify
859 credentials, you should also specify secure=True so that your userid and
860 password are not passed in cleartext across the wire.
861
Benjamin Petersona90e92d2014-11-23 20:38:37 -0600862 .. versionchanged:: 3.5
Benjamin Peterson43052a12014-11-23 20:36:44 -0600863 The *context* parameter was added.
864
Vinay Sajipc673a9a2014-05-30 18:59:27 +0100865 .. method:: mapLogRecord(record)
866
867 Provides a dictionary, based on ``record``, which is to be URL-encoded
868 and sent to the web server. The default implementation just returns
869 ``record.__dict__``. This method can be overridden if e.g. only a
870 subset of :class:`~logging.LogRecord` is to be sent to the web server, or
871 if more specific customization of what's sent to the server is required.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000872
873 .. method:: emit(record)
874
Vinay Sajipc673a9a2014-05-30 18:59:27 +0100875 Sends the record to the Web server as an URL-encoded dictionary. The
876 :meth:`mapLogRecord` method is used to convert the record to the
877 dictionary to be sent.
878
Berker Peksag9c1dba22014-09-28 00:00:58 +0300879 .. note:: Since preparing a record for sending it to a Web server is not
Vinay Sajipc673a9a2014-05-30 18:59:27 +0100880 the same as a generic formatting operation, using
881 :meth:`~logging.Handler.setFormatter` to specify a
882 :class:`~logging.Formatter` for a :class:`HTTPHandler` has no effect.
883 Instead of calling :meth:`~logging.Handler.format`, this handler calls
884 :meth:`mapLogRecord` and then :func:`urllib.parse.urlencode` to encode the
885 dictionary in a form suitable for sending to a Web server.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000886
887
888.. _queue-handler:
889
890
891QueueHandler
892^^^^^^^^^^^^
893
894.. versionadded:: 3.2
895
896The :class:`QueueHandler` class, located in the :mod:`logging.handlers` module,
897supports sending logging messages to a queue, such as those implemented in the
898:mod:`queue` or :mod:`multiprocessing` modules.
899
900Along with the :class:`QueueListener` class, :class:`QueueHandler` can be used
901to let handlers do their work on a separate thread from the one which does the
902logging. This is important in Web applications and also other service
903applications where threads servicing clients need to respond as quickly as
904possible, while any potentially slow operations (such as sending an email via
905:class:`SMTPHandler`) are done on a separate thread.
906
907.. class:: QueueHandler(queue)
908
909 Returns a new instance of the :class:`QueueHandler` class. The instance is
910 initialized with the queue to send messages to. The queue can be any queue-
911 like object; it's used as-is by the :meth:`enqueue` method, which needs
912 to know how to send messages to it.
913
914
915 .. method:: emit(record)
916
917 Enqueues the result of preparing the LogRecord.
918
919 .. method:: prepare(record)
920
921 Prepares a record for queuing. The object returned by this
922 method is enqueued.
923
924 The base implementation formats the record to merge the message
925 and arguments, and removes unpickleable items from the record
926 in-place.
927
928 You might want to override this method if you want to convert
929 the record to a dict or JSON string, or send a modified copy
930 of the record while leaving the original intact.
931
932 .. method:: enqueue(record)
933
934 Enqueues the record on the queue using ``put_nowait()``; you may
935 want to override this if you want to use blocking behaviour, or a
Vinay Sajip9c10d6b2013-11-15 20:58:13 +0000936 timeout, or a customized queue implementation.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000937
938
939
Éric Araujo5eada942011-08-19 00:41:23 +0200940.. _queue-listener:
Vinay Sajipc63619b2010-12-19 12:56:57 +0000941
942QueueListener
943^^^^^^^^^^^^^
944
945.. versionadded:: 3.2
946
947The :class:`QueueListener` class, located in the :mod:`logging.handlers`
948module, supports receiving logging messages from a queue, such as those
949implemented in the :mod:`queue` or :mod:`multiprocessing` modules. The
950messages are received from a queue in an internal thread and passed, on
951the same thread, to one or more handlers for processing. While
952:class:`QueueListener` is not itself a handler, it is documented here
953because it works hand-in-hand with :class:`QueueHandler`.
954
955Along with the :class:`QueueHandler` class, :class:`QueueListener` can be used
956to let handlers do their work on a separate thread from the one which does the
957logging. This is important in Web applications and also other service
958applications where threads servicing clients need to respond as quickly as
959possible, while any potentially slow operations (such as sending an email via
960:class:`SMTPHandler`) are done on a separate thread.
961
Vinay Sajip365701a2015-02-09 19:49:00 +0000962.. class:: QueueListener(queue, *handlers, respect_handler_level=False)
Vinay Sajipc63619b2010-12-19 12:56:57 +0000963
964 Returns a new instance of the :class:`QueueListener` class. The instance is
965 initialized with the queue to send messages to and a list of handlers which
966 will handle entries placed on the queue. The queue can be any queue-
967 like object; it's passed as-is to the :meth:`dequeue` method, which needs
Vinay Sajip365701a2015-02-09 19:49:00 +0000968 to know how to get messages from it. If ``respect_handler_level`` is ``True``,
969 a handler's level is respected (compared with the level for the message) when
970 deciding whether to pass messages to that handler; otherwise, the behaviour
971 is as in previous Python versions - to always pass each message to each
972 handler.
973
974 .. versionchanged:: 3.5
975 The ``respect_handler_levels`` argument was added.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000976
977 .. method:: dequeue(block)
978
979 Dequeues a record and return it, optionally blocking.
980
981 The base implementation uses ``get()``. You may want to override this
982 method if you want to use timeouts or work with custom queue
983 implementations.
984
985 .. method:: prepare(record)
986
987 Prepare a record for handling.
988
989 This implementation just returns the passed-in record. You may want to
990 override this method if you need to do any custom marshalling or
991 manipulation of the record before passing it to the handlers.
992
993 .. method:: handle(record)
994
995 Handle a record.
996
997 This just loops through the handlers offering them the record
998 to handle. The actual object passed to the handlers is that which
999 is returned from :meth:`prepare`.
1000
1001 .. method:: start()
1002
1003 Starts the listener.
1004
1005 This starts up a background thread to monitor the queue for
1006 LogRecords to process.
1007
1008 .. method:: stop()
1009
1010 Stops the listener.
1011
1012 This asks the thread to terminate, and then waits for it to do so.
1013 Note that if you don't call this before your application exits, there
1014 may be some records still left on the queue, which won't be processed.
1015
Vinay Sajipa29a9dd2011-02-25 16:05:26 +00001016 .. method:: enqueue_sentinel()
1017
1018 Writes a sentinel to the queue to tell the listener to quit. This
1019 implementation uses ``put_nowait()``. You may want to override this
1020 method if you want to use timeouts or work with custom queue
1021 implementations.
1022
1023 .. versionadded:: 3.3
1024
Vinay Sajipc63619b2010-12-19 12:56:57 +00001025
1026.. seealso::
1027
1028 Module :mod:`logging`
1029 API reference for the logging module.
1030
1031 Module :mod:`logging.config`
1032 Configuration API for the logging module.
1033
1034