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