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