blob: 810a473350a742943c4f1d84cc11a240d36bc18a [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
48 is then written to the stream with a trailing newline. If exception
49 information is present, it is formatted using
50 :func:`traceback.print_exception` and appended to the stream.
51
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.
64
65.. _file-handler:
66
67FileHandler
68^^^^^^^^^^^
69
70The :class:`FileHandler` class, located in the core :mod:`logging` package,
71sends logging output to a disk file. It inherits the output functionality from
72:class:`StreamHandler`.
73
74
75.. class:: FileHandler(filename, mode='a', encoding=None, delay=False)
76
77 Returns a new instance of the :class:`FileHandler` class. The specified file is
78 opened and used as the stream for logging. If *mode* is not specified,
79 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
80 with that encoding. If *delay* is true, then file opening is deferred until the
81 first call to :meth:`emit`. By default, the file grows indefinitely.
82
83
84 .. method:: close()
85
86 Closes the file.
87
88
89 .. method:: emit(record)
90
91 Outputs the record to the file.
92
93
94.. _null-handler:
95
96NullHandler
97^^^^^^^^^^^
98
99.. versionadded:: 3.1
100
101The :class:`NullHandler` class, located in the core :mod:`logging` package,
102does not do any formatting or output. It is essentially a 'no-op' handler
103for use by library developers.
104
105.. class:: NullHandler()
106
107 Returns a new instance of the :class:`NullHandler` class.
108
109 .. method:: emit(record)
110
111 This method does nothing.
112
113 .. method:: handle(record)
114
115 This method does nothing.
116
117 .. method:: createLock()
118
119 This method returns ``None`` for the lock, since there is no
120 underlying I/O to which access needs to be serialized.
121
122
123See :ref:`library-config` for more information on how to use
124:class:`NullHandler`.
125
126.. _watched-file-handler:
127
128WatchedFileHandler
129^^^^^^^^^^^^^^^^^^
130
131.. currentmodule:: logging.handlers
132
133The :class:`WatchedFileHandler` class, located in the :mod:`logging.handlers`
134module, is a :class:`FileHandler` which watches the file it is logging to. If
135the file changes, it is closed and reopened using the file name.
136
137A file change can happen because of usage of programs such as *newsyslog* and
138*logrotate* which perform log file rotation. This handler, intended for use
139under Unix/Linux, watches the file to see if it has changed since the last emit.
140(A file is deemed to have changed if its device or inode have changed.) If the
141file has changed, the old file stream is closed, and the file opened to get a
142new stream.
143
144This handler is not appropriate for use under Windows, because under Windows
145open log files cannot be moved or renamed - logging opens the files with
146exclusive locks - and so there is no need for such a handler. Furthermore,
147*ST_INO* is not supported under Windows; :func:`stat` always returns zero for
148this value.
149
150
151.. class:: WatchedFileHandler(filename[,mode[, encoding[, delay]]])
152
153 Returns a new instance of the :class:`WatchedFileHandler` class. The specified
154 file is opened and used as the stream for logging. If *mode* is not specified,
155 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
156 with that encoding. If *delay* is true, then file opening is deferred until the
157 first call to :meth:`emit`. By default, the file grows indefinitely.
158
159
160 .. method:: emit(record)
161
162 Outputs the record to the file, but first checks to see if the file has
163 changed. If it has, the existing stream is flushed and closed and the
164 file opened again, before outputting the record to the file.
165
166.. _rotating-file-handler:
167
168RotatingFileHandler
169^^^^^^^^^^^^^^^^^^^
170
171The :class:`RotatingFileHandler` class, located in the :mod:`logging.handlers`
172module, supports rotation of disk log files.
173
174
175.. class:: RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0)
176
177 Returns a new instance of the :class:`RotatingFileHandler` class. The specified
178 file is opened and used as the stream for logging. If *mode* is not specified,
179 ``'a'`` is used. If *encoding* is not *None*, it is used to open the file
180 with that encoding. If *delay* is true, then file opening is deferred until the
181 first call to :meth:`emit`. By default, the file grows indefinitely.
182
183 You can use the *maxBytes* and *backupCount* values to allow the file to
184 :dfn:`rollover` at a predetermined size. When the size is about to be exceeded,
185 the file is closed and a new file is silently opened for output. Rollover occurs
186 whenever the current log file is nearly *maxBytes* in length; if *maxBytes* is
187 zero, rollover never occurs. If *backupCount* is non-zero, the system will save
188 old log files by appending the extensions '.1', '.2' etc., to the filename. For
189 example, with a *backupCount* of 5 and a base file name of :file:`app.log`, you
190 would get :file:`app.log`, :file:`app.log.1`, :file:`app.log.2`, up to
191 :file:`app.log.5`. The file being written to is always :file:`app.log`. When
192 this file is filled, it is closed and renamed to :file:`app.log.1`, and if files
193 :file:`app.log.1`, :file:`app.log.2`, etc. exist, then they are renamed to
194 :file:`app.log.2`, :file:`app.log.3` etc. respectively.
195
196
197 .. method:: doRollover()
198
199 Does a rollover, as described above.
200
201
202 .. method:: emit(record)
203
204 Outputs the record to the file, catering for rollover as described
205 previously.
206
207.. _timed-rotating-file-handler:
208
209TimedRotatingFileHandler
210^^^^^^^^^^^^^^^^^^^^^^^^
211
212The :class:`TimedRotatingFileHandler` class, located in the
213:mod:`logging.handlers` module, supports rotation of disk log files at certain
214timed intervals.
215
216
217.. class:: TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False)
218
219 Returns a new instance of the :class:`TimedRotatingFileHandler` class. The
220 specified file is opened and used as the stream for logging. On rotating it also
221 sets the filename suffix. Rotating happens based on the product of *when* and
222 *interval*.
223
224 You can use the *when* to specify the type of *interval*. The list of possible
225 values is below. Note that they are not case sensitive.
226
227 +----------------+-----------------------+
228 | Value | Type of interval |
229 +================+=======================+
230 | ``'S'`` | Seconds |
231 +----------------+-----------------------+
232 | ``'M'`` | Minutes |
233 +----------------+-----------------------+
234 | ``'H'`` | Hours |
235 +----------------+-----------------------+
236 | ``'D'`` | Days |
237 +----------------+-----------------------+
238 | ``'W'`` | Week day (0=Monday) |
239 +----------------+-----------------------+
240 | ``'midnight'`` | Roll over at midnight |
241 +----------------+-----------------------+
242
243 The system will save old log files by appending extensions to the filename.
244 The extensions are date-and-time based, using the strftime format
245 ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on the
246 rollover interval.
247
248 When computing the next rollover time for the first time (when the handler
249 is created), the last modification time of an existing log file, or else
250 the current time, is used to compute when the next rotation will occur.
251
252 If the *utc* argument is true, times in UTC will be used; otherwise
253 local time is used.
254
255 If *backupCount* is nonzero, at most *backupCount* files
256 will be kept, and if more would be created when rollover occurs, the oldest
257 one is deleted. The deletion logic uses the interval to determine which
258 files to delete, so changing the interval may leave old files lying around.
259
260 If *delay* is true, then file opening is deferred until the first call to
261 :meth:`emit`.
262
263
264 .. method:: doRollover()
265
266 Does a rollover, as described above.
267
268
269 .. method:: emit(record)
270
271 Outputs the record to the file, catering for rollover as described above.
272
273
274.. _socket-handler:
275
276SocketHandler
277^^^^^^^^^^^^^
278
279The :class:`SocketHandler` class, located in the :mod:`logging.handlers` module,
280sends logging output to a network socket. The base class uses a TCP socket.
281
282
283.. class:: SocketHandler(host, port)
284
285 Returns a new instance of the :class:`SocketHandler` class intended to
286 communicate with a remote machine whose address is given by *host* and *port*.
287
288
289 .. method:: close()
290
291 Closes the socket.
292
293
294 .. method:: emit()
295
296 Pickles the record's attribute dictionary and writes it to the socket in
297 binary format. If there is an error with the socket, silently drops the
298 packet. If the connection was previously lost, re-establishes the
299 connection. To unpickle the record at the receiving end into a
300 :class:`LogRecord`, use the :func:`makeLogRecord` function.
301
302
303 .. method:: handleError()
304
305 Handles an error which has occurred during :meth:`emit`. The most likely
306 cause is a lost connection. Closes the socket so that we can retry on the
307 next event.
308
309
310 .. method:: makeSocket()
311
312 This is a factory method which allows subclasses to define the precise
313 type of socket they want. The default implementation creates a TCP socket
314 (:const:`socket.SOCK_STREAM`).
315
316
317 .. method:: makePickle(record)
318
319 Pickles the record's attribute dictionary in binary format with a length
320 prefix, and returns it ready for transmission across the socket.
321
322 Note that pickles aren't completely secure. If you are concerned about
323 security, you may want to override this method to implement a more secure
324 mechanism. For example, you can sign pickles using HMAC and then verify
325 them on the receiving end, or alternatively you can disable unpickling of
326 global objects on the receiving end.
327
328 .. method:: send(packet)
329
330 Send a pickled string *packet* to the socket. This function allows for
331 partial sends which can happen when the network is busy.
332
333
334.. _datagram-handler:
335
336DatagramHandler
337^^^^^^^^^^^^^^^
338
339The :class:`DatagramHandler` class, located in the :mod:`logging.handlers`
340module, inherits from :class:`SocketHandler` to support sending logging messages
341over UDP sockets.
342
343
344.. class:: DatagramHandler(host, port)
345
346 Returns a new instance of the :class:`DatagramHandler` class intended to
347 communicate with a remote machine whose address is given by *host* and *port*.
348
349
350 .. method:: emit()
351
352 Pickles the record's attribute dictionary and writes it to the socket in
353 binary format. If there is an error with the socket, silently drops the
354 packet. To unpickle the record at the receiving end into a
355 :class:`LogRecord`, use the :func:`makeLogRecord` function.
356
357
358 .. method:: makeSocket()
359
360 The factory method of :class:`SocketHandler` is here overridden to create
361 a UDP socket (:const:`socket.SOCK_DGRAM`).
362
363
364 .. method:: send(s)
365
366 Send a pickled string to a socket.
367
368
369.. _syslog-handler:
370
371SysLogHandler
372^^^^^^^^^^^^^
373
374The :class:`SysLogHandler` class, located in the :mod:`logging.handlers` module,
375supports sending logging messages to a remote or local Unix syslog.
376
377
378.. class:: SysLogHandler(address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER, socktype=socket.SOCK_DGRAM)
379
380 Returns a new instance of the :class:`SysLogHandler` class intended to
381 communicate with a remote Unix machine whose address is given by *address* in
382 the form of a ``(host, port)`` tuple. If *address* is not specified,
383 ``('localhost', 514)`` is used. The address is used to open a socket. An
384 alternative to providing a ``(host, port)`` tuple is providing an address as a
385 string, for example '/dev/log'. In this case, a Unix domain socket is used to
386 send the message to the syslog. If *facility* is not specified,
387 :const:`LOG_USER` is used. The type of socket opened depends on the
388 *socktype* argument, which defaults to :const:`socket.SOCK_DGRAM` and thus
389 opens a UDP socket. To open a TCP socket (for use with the newer syslog
390 daemons such as rsyslog), specify a value of :const:`socket.SOCK_STREAM`.
391
392 Note that if your server is not listening on UDP port 514,
393 :class:`SysLogHandler` may appear not to work. In that case, check what
394 address you should be using for a domain socket - it's system dependent.
395 For example, on Linux it's usually '/dev/log' but on OS/X it's
396 '/var/run/syslog'. You'll need to check your platform and use the
397 appropriate address (you may need to do this check at runtime if your
398 application needs to run on several platforms). On Windows, you pretty
399 much have to use the UDP option.
400
401 .. versionchanged:: 3.2
402 *socktype* was added.
403
404
405 .. method:: close()
406
407 Closes the socket to the remote host.
408
409
410 .. method:: emit(record)
411
412 The record is formatted, and then sent to the syslog server. If exception
413 information is present, it is *not* sent to the server.
414
415
416 .. method:: encodePriority(facility, priority)
417
418 Encodes the facility and priority into an integer. You can pass in strings
419 or integers - if strings are passed, internal mapping dictionaries are
420 used to convert them to integers.
421
422 The symbolic ``LOG_`` values are defined in :class:`SysLogHandler` and
423 mirror the values defined in the ``sys/syslog.h`` header file.
424
425 **Priorities**
426
427 +--------------------------+---------------+
428 | Name (string) | Symbolic value|
429 +==========================+===============+
430 | ``alert`` | LOG_ALERT |
431 +--------------------------+---------------+
432 | ``crit`` or ``critical`` | LOG_CRIT |
433 +--------------------------+---------------+
434 | ``debug`` | LOG_DEBUG |
435 +--------------------------+---------------+
436 | ``emerg`` or ``panic`` | LOG_EMERG |
437 +--------------------------+---------------+
438 | ``err`` or ``error`` | LOG_ERR |
439 +--------------------------+---------------+
440 | ``info`` | LOG_INFO |
441 +--------------------------+---------------+
442 | ``notice`` | LOG_NOTICE |
443 +--------------------------+---------------+
444 | ``warn`` or ``warning`` | LOG_WARNING |
445 +--------------------------+---------------+
446
447 **Facilities**
448
449 +---------------+---------------+
450 | Name (string) | Symbolic value|
451 +===============+===============+
452 | ``auth`` | LOG_AUTH |
453 +---------------+---------------+
454 | ``authpriv`` | LOG_AUTHPRIV |
455 +---------------+---------------+
456 | ``cron`` | LOG_CRON |
457 +---------------+---------------+
458 | ``daemon`` | LOG_DAEMON |
459 +---------------+---------------+
460 | ``ftp`` | LOG_FTP |
461 +---------------+---------------+
462 | ``kern`` | LOG_KERN |
463 +---------------+---------------+
464 | ``lpr`` | LOG_LPR |
465 +---------------+---------------+
466 | ``mail`` | LOG_MAIL |
467 +---------------+---------------+
468 | ``news`` | LOG_NEWS |
469 +---------------+---------------+
470 | ``syslog`` | LOG_SYSLOG |
471 +---------------+---------------+
472 | ``user`` | LOG_USER |
473 +---------------+---------------+
474 | ``uucp`` | LOG_UUCP |
475 +---------------+---------------+
476 | ``local0`` | LOG_LOCAL0 |
477 +---------------+---------------+
478 | ``local1`` | LOG_LOCAL1 |
479 +---------------+---------------+
480 | ``local2`` | LOG_LOCAL2 |
481 +---------------+---------------+
482 | ``local3`` | LOG_LOCAL3 |
483 +---------------+---------------+
484 | ``local4`` | LOG_LOCAL4 |
485 +---------------+---------------+
486 | ``local5`` | LOG_LOCAL5 |
487 +---------------+---------------+
488 | ``local6`` | LOG_LOCAL6 |
489 +---------------+---------------+
490 | ``local7`` | LOG_LOCAL7 |
491 +---------------+---------------+
492
493 .. method:: mapPriority(levelname)
494
495 Maps a logging level name to a syslog priority name.
496 You may need to override this if you are using custom levels, or
497 if the default algorithm is not suitable for your needs. The
498 default algorithm maps ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and
499 ``CRITICAL`` to the equivalent syslog names, and all other level
500 names to 'warning'.
501
502.. _nt-eventlog-handler:
503
504NTEventLogHandler
505^^^^^^^^^^^^^^^^^
506
507The :class:`NTEventLogHandler` class, located in the :mod:`logging.handlers`
508module, supports sending logging messages to a local Windows NT, Windows 2000 or
509Windows XP event log. Before you can use it, you need Mark Hammond's Win32
510extensions for Python installed.
511
512
513.. class:: NTEventLogHandler(appname, dllname=None, logtype='Application')
514
515 Returns a new instance of the :class:`NTEventLogHandler` class. The *appname* is
516 used to define the application name as it appears in the event log. An
517 appropriate registry entry is created using this name. The *dllname* should give
518 the fully qualified pathname of a .dll or .exe which contains message
519 definitions to hold in the log (if not specified, ``'win32service.pyd'`` is used
520 - this is installed with the Win32 extensions and contains some basic
521 placeholder message definitions. Note that use of these placeholders will make
522 your event logs big, as the entire message source is held in the log. If you
523 want slimmer logs, you have to pass in the name of your own .dll or .exe which
524 contains the message definitions you want to use in the event log). The
525 *logtype* is one of ``'Application'``, ``'System'`` or ``'Security'``, and
526 defaults to ``'Application'``.
527
528
529 .. method:: close()
530
531 At this point, you can remove the application name from the registry as a
532 source of event log entries. However, if you do this, you will not be able
533 to see the events as you intended in the Event Log Viewer - it needs to be
534 able to access the registry to get the .dll name. The current version does
535 not do this.
536
537
538 .. method:: emit(record)
539
540 Determines the message ID, event category and event type, and then logs
541 the message in the NT event log.
542
543
544 .. method:: getEventCategory(record)
545
546 Returns the event category for the record. Override this if you want to
547 specify your own categories. This version returns 0.
548
549
550 .. method:: getEventType(record)
551
552 Returns the event type for the record. Override this if you want to
553 specify your own types. This version does a mapping using the handler's
554 typemap attribute, which is set up in :meth:`__init__` to a dictionary
555 which contains mappings for :const:`DEBUG`, :const:`INFO`,
556 :const:`WARNING`, :const:`ERROR` and :const:`CRITICAL`. If you are using
557 your own levels, you will either need to override this method or place a
558 suitable dictionary in the handler's *typemap* attribute.
559
560
561 .. method:: getMessageID(record)
562
563 Returns the message ID for the record. If you are using your own messages,
564 you could do this by having the *msg* passed to the logger being an ID
565 rather than a format string. Then, in here, you could use a dictionary
566 lookup to get the message ID. This version returns 1, which is the base
567 message ID in :file:`win32service.pyd`.
568
569.. _smtp-handler:
570
571SMTPHandler
572^^^^^^^^^^^
573
574The :class:`SMTPHandler` class, located in the :mod:`logging.handlers` module,
575supports sending logging messages to an email address via SMTP.
576
577
578.. class:: SMTPHandler(mailhost, fromaddr, toaddrs, subject, credentials=None)
579
580 Returns a new instance of the :class:`SMTPHandler` class. The instance is
581 initialized with the from and to addresses and subject line of the email. The
582 *toaddrs* should be a list of strings. To specify a non-standard SMTP port, use
583 the (host, port) tuple format for the *mailhost* argument. If you use a string,
584 the standard SMTP port is used. If your SMTP server requires authentication, you
585 can specify a (username, password) tuple for the *credentials* argument.
586
587
588 .. method:: emit(record)
589
590 Formats the record and sends it to the specified addressees.
591
592
593 .. method:: getSubject(record)
594
595 If you want to specify a subject line which is record-dependent, override
596 this method.
597
598.. _memory-handler:
599
600MemoryHandler
601^^^^^^^^^^^^^
602
603The :class:`MemoryHandler` class, located in the :mod:`logging.handlers` module,
604supports buffering of logging records in memory, periodically flushing them to a
605:dfn:`target` handler. Flushing occurs whenever the buffer is full, or when an
606event of a certain severity or greater is seen.
607
608:class:`MemoryHandler` is a subclass of the more general
609:class:`BufferingHandler`, which is an abstract class. This buffers logging
610records in memory. Whenever each record is added to the buffer, a check is made
611by calling :meth:`shouldFlush` to see if the buffer should be flushed. If it
612should, then :meth:`flush` is expected to do the needful.
613
614
615.. class:: BufferingHandler(capacity)
616
617 Initializes the handler with a buffer of the specified capacity.
618
619
620 .. method:: emit(record)
621
622 Appends the record to the buffer. If :meth:`shouldFlush` returns true,
623 calls :meth:`flush` to process the buffer.
624
625
626 .. method:: flush()
627
628 You can override this to implement custom flushing behavior. This version
629 just zaps the buffer to empty.
630
631
632 .. method:: shouldFlush(record)
633
634 Returns true if the buffer is up to capacity. This method can be
635 overridden to implement custom flushing strategies.
636
637
638.. class:: MemoryHandler(capacity, flushLevel=ERROR, target=None)
639
640 Returns a new instance of the :class:`MemoryHandler` class. The instance is
641 initialized with a buffer size of *capacity*. If *flushLevel* is not specified,
642 :const:`ERROR` is used. If no *target* is specified, the target will need to be
643 set using :meth:`setTarget` before this handler does anything useful.
644
645
646 .. method:: close()
647
648 Calls :meth:`flush`, sets the target to :const:`None` and clears the
649 buffer.
650
651
652 .. method:: flush()
653
654 For a :class:`MemoryHandler`, flushing means just sending the buffered
655 records to the target, if there is one. The buffer is also cleared when
656 this happens. Override if you want different behavior.
657
658
659 .. method:: setTarget(target)
660
661 Sets the target handler for this handler.
662
663
664 .. method:: shouldFlush(record)
665
666 Checks for buffer full or a record at the *flushLevel* or higher.
667
668
669.. _http-handler:
670
671HTTPHandler
672^^^^^^^^^^^
673
674The :class:`HTTPHandler` class, located in the :mod:`logging.handlers` module,
675supports sending logging messages to a Web server, using either ``GET`` or
676``POST`` semantics.
677
678
679.. class:: HTTPHandler(host, url, method='GET', secure=False, credentials=None)
680
681 Returns a new instance of the :class:`HTTPHandler` class. The *host* can be
682 of the form ``host:port``, should you need to use a specific port number.
683 If no *method* is specified, ``GET`` is used. If *secure* is True, an HTTPS
684 connection will be used. If *credentials* is specified, it should be a
685 2-tuple consisting of userid and password, which will be placed in an HTTP
686 'Authorization' header using Basic authentication. If you specify
687 credentials, you should also specify secure=True so that your userid and
688 password are not passed in cleartext across the wire.
689
690
691 .. method:: emit(record)
692
693 Sends the record to the Web server as a percent-encoded dictionary.
694
695
696.. _queue-handler:
697
698
699QueueHandler
700^^^^^^^^^^^^
701
702.. versionadded:: 3.2
703
704The :class:`QueueHandler` class, located in the :mod:`logging.handlers` module,
705supports sending logging messages to a queue, such as those implemented in the
706:mod:`queue` or :mod:`multiprocessing` modules.
707
708Along with the :class:`QueueListener` class, :class:`QueueHandler` can be used
709to let handlers do their work on a separate thread from the one which does the
710logging. This is important in Web applications and also other service
711applications where threads servicing clients need to respond as quickly as
712possible, while any potentially slow operations (such as sending an email via
713:class:`SMTPHandler`) are done on a separate thread.
714
715.. class:: QueueHandler(queue)
716
717 Returns a new instance of the :class:`QueueHandler` class. The instance is
718 initialized with the queue to send messages to. The queue can be any queue-
719 like object; it's used as-is by the :meth:`enqueue` method, which needs
720 to know how to send messages to it.
721
722
723 .. method:: emit(record)
724
725 Enqueues the result of preparing the LogRecord.
726
727 .. method:: prepare(record)
728
729 Prepares a record for queuing. The object returned by this
730 method is enqueued.
731
732 The base implementation formats the record to merge the message
733 and arguments, and removes unpickleable items from the record
734 in-place.
735
736 You might want to override this method if you want to convert
737 the record to a dict or JSON string, or send a modified copy
738 of the record while leaving the original intact.
739
740 .. method:: enqueue(record)
741
742 Enqueues the record on the queue using ``put_nowait()``; you may
743 want to override this if you want to use blocking behaviour, or a
744 timeout, or a customised queue implementation.
745
746
747
748.. queue-listener:
749
750QueueListener
751^^^^^^^^^^^^^
752
753.. versionadded:: 3.2
754
755The :class:`QueueListener` class, located in the :mod:`logging.handlers`
756module, supports receiving logging messages from a queue, such as those
757implemented in the :mod:`queue` or :mod:`multiprocessing` modules. The
758messages are received from a queue in an internal thread and passed, on
759the same thread, to one or more handlers for processing. While
760:class:`QueueListener` is not itself a handler, it is documented here
761because it works hand-in-hand with :class:`QueueHandler`.
762
763Along with the :class:`QueueHandler` class, :class:`QueueListener` can be used
764to let handlers do their work on a separate thread from the one which does the
765logging. This is important in Web applications and also other service
766applications where threads servicing clients need to respond as quickly as
767possible, while any potentially slow operations (such as sending an email via
768:class:`SMTPHandler`) are done on a separate thread.
769
770.. class:: QueueListener(queue, *handlers)
771
772 Returns a new instance of the :class:`QueueListener` class. The instance is
773 initialized with the queue to send messages to and a list of handlers which
774 will handle entries placed on the queue. The queue can be any queue-
775 like object; it's passed as-is to the :meth:`dequeue` method, which needs
776 to know how to get messages from it.
777
778 .. method:: dequeue(block)
779
780 Dequeues a record and return it, optionally blocking.
781
782 The base implementation uses ``get()``. You may want to override this
783 method if you want to use timeouts or work with custom queue
784 implementations.
785
786 .. method:: prepare(record)
787
788 Prepare a record for handling.
789
790 This implementation just returns the passed-in record. You may want to
791 override this method if you need to do any custom marshalling or
792 manipulation of the record before passing it to the handlers.
793
794 .. method:: handle(record)
795
796 Handle a record.
797
798 This just loops through the handlers offering them the record
799 to handle. The actual object passed to the handlers is that which
800 is returned from :meth:`prepare`.
801
802 .. method:: start()
803
804 Starts the listener.
805
806 This starts up a background thread to monitor the queue for
807 LogRecords to process.
808
809 .. method:: stop()
810
811 Stops the listener.
812
813 This asks the thread to terminate, and then waits for it to do so.
814 Note that if you don't call this before your application exits, there
815 may be some records still left on the queue, which won't be processed.
816
817
818.. seealso::
819
820 Module :mod:`logging`
821 API reference for the logging module.
822
823 Module :mod:`logging.config`
824 Configuration API for the logging module.
825
826