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