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