blob: eccd0ae41da776ef1938426a03152ddf3cffa686 [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
Vinay Sajipc63619b2010-12-19 12:56:57 +00007.. moduleauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
8.. sectionauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
9
Terry Jan Reedyfa089b92016-06-11 15:02:54 -040010**Source code:** :source:`Lib/logging/handlers.py`
11
Vinay Sajip01094e12010-12-19 13:41:26 +000012.. sidebar:: Important
13
14 This page contains only reference information. For tutorials,
15 please see
16
17 * :ref:`Basic Tutorial <logging-basic-tutorial>`
18 * :ref:`Advanced Tutorial <logging-advanced-tutorial>`
19 * :ref:`Logging Cookbook <logging-cookbook>`
Vinay Sajipc63619b2010-12-19 12:56:57 +000020
Vinay Sajip31b862d2013-09-05 23:01:07 +010021--------------
22
Vinay Sajipc63619b2010-12-19 12:56:57 +000023.. currentmodule:: logging
24
Vinay Sajip01094e12010-12-19 13:41:26 +000025The following useful handlers are provided in the package. Note that three of
26the handlers (:class:`StreamHandler`, :class:`FileHandler` and
27:class:`NullHandler`) are actually defined in the :mod:`logging` module itself,
28but have been documented here along with the other handlers.
29
Vinay Sajipc63619b2010-12-19 12:56:57 +000030.. _stream-handler:
31
32StreamHandler
33^^^^^^^^^^^^^
34
35The :class:`StreamHandler` class, located in the core :mod:`logging` package,
36sends logging output to streams such as *sys.stdout*, *sys.stderr* or any
37file-like object (or, more precisely, any object which supports :meth:`write`
38and :meth:`flush` methods).
39
40
41.. class:: StreamHandler(stream=None)
42
43 Returns a new instance of the :class:`StreamHandler` class. If *stream* is
44 specified, the instance will use it for logging output; otherwise, *sys.stderr*
45 will be used.
46
47
48 .. method:: emit(record)
49
50 If a formatter is specified, it is used to format the record. The record
Andre Delfino3e658302019-06-29 18:59:49 -030051 is then written to the stream followed by :attr:`terminator`. If exception information
Vinay Sajip689b68a2010-12-22 15:04:15 +000052 is present, it is formatted using :func:`traceback.print_exception` and
53 appended to the stream.
Vinay Sajipc63619b2010-12-19 12:56:57 +000054
55
56 .. method:: flush()
57
58 Flushes the stream by calling its :meth:`flush` method. Note that the
Vinay Sajip67f39772013-08-17 00:39:42 +010059 :meth:`close` method is inherited from :class:`~logging.Handler` and so
60 does no output, so an explicit :meth:`flush` call may be needed at times.
Vinay Sajipc63619b2010-12-19 12:56:57 +000061
Vinay Sajip2543f502017-07-30 10:41:45 +010062 .. method:: setStream(stream)
63
64 Sets the instance's stream to the specified value, if it is different.
65 The old stream is flushed before the new stream is set.
66
67 :param stream: The stream that the handler should use.
68
69 :return: the old stream, if the stream was changed, or *None* if it wasn't.
70
Andre Delfino18a2fc62019-06-29 18:57:39 -030071 .. versionadded:: 3.7
Vinay Sajip2543f502017-07-30 10:41:45 +010072
Andre Delfino3e658302019-06-29 18:59:49 -030073 .. attribute:: terminator
Vinay Sajip2543f502017-07-30 10:41:45 +010074
Andre Delfino3e658302019-06-29 18:59:49 -030075 String used as the terminator when writing a formatted record to a stream.
76 Default value is ``'\n'``.
77
78 If you don't want a newline termination, you can set the handler instance's
79 ``terminator`` attribute to the empty string.
80
81 In earlier versions, the terminator was hardcoded as ``'\n'``.
82
83 .. versionadded:: 3.2
Vinay Sajipc63619b2010-12-19 12:56:57 +000084
Vinay Sajip2543f502017-07-30 10:41:45 +010085
Vinay Sajipc63619b2010-12-19 12:56:57 +000086.. _file-handler:
87
88FileHandler
89^^^^^^^^^^^
90
91The :class:`FileHandler` class, located in the core :mod:`logging` package,
92sends logging output to a disk file. It inherits the output functionality from
93:class:`StreamHandler`.
94
95
Vinay Sajipca7b5042019-06-17 17:40:52 +010096.. class:: FileHandler(filename, mode='a', encoding=None, delay=False, errors=None)
Vinay Sajipc63619b2010-12-19 12:56:57 +000097
98 Returns a new instance of the :class:`FileHandler` class. The specified file is
99 opened and used as the stream for logging. If *mode* is not specified,
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300100 :const:`'a'` is used. If *encoding* is not ``None``, it is used to open the file
Vinay Sajipc63619b2010-12-19 12:56:57 +0000101 with that encoding. If *delay* is true, then file opening is deferred until the
Vinay Sajipca7b5042019-06-17 17:40:52 +0100102 first call to :meth:`emit`. By default, the file grows indefinitely. If
103 *errors* is specified, it's used to determine how encoding errors are handled.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000104
Vinay Sajip638e6222016-07-22 18:23:04 +0100105 .. versionchanged:: 3.6
106 As well as string values, :class:`~pathlib.Path` objects are also accepted
107 for the *filename* argument.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000108
Vinay Sajipca7b5042019-06-17 17:40:52 +0100109 .. versionchanged:: 3.9
110 The *errors* parameter was added.
111
Vinay Sajipc63619b2010-12-19 12:56:57 +0000112 .. method:: close()
113
114 Closes the file.
115
Vinay Sajipc63619b2010-12-19 12:56:57 +0000116 .. method:: emit(record)
117
118 Outputs the record to the file.
119
120
121.. _null-handler:
122
123NullHandler
124^^^^^^^^^^^
125
126.. versionadded:: 3.1
127
128The :class:`NullHandler` class, located in the core :mod:`logging` package,
129does not do any formatting or output. It is essentially a 'no-op' handler
130for use by library developers.
131
132.. class:: NullHandler()
133
134 Returns a new instance of the :class:`NullHandler` class.
135
136 .. method:: emit(record)
137
138 This method does nothing.
139
140 .. method:: handle(record)
141
142 This method does nothing.
143
144 .. method:: createLock()
145
146 This method returns ``None`` for the lock, since there is no
147 underlying I/O to which access needs to be serialized.
148
149
150See :ref:`library-config` for more information on how to use
151:class:`NullHandler`.
152
153.. _watched-file-handler:
154
155WatchedFileHandler
156^^^^^^^^^^^^^^^^^^
157
158.. currentmodule:: logging.handlers
159
160The :class:`WatchedFileHandler` class, located in the :mod:`logging.handlers`
161module, is a :class:`FileHandler` which watches the file it is logging to. If
162the file changes, it is closed and reopened using the file name.
163
164A file change can happen because of usage of programs such as *newsyslog* and
165*logrotate* which perform log file rotation. This handler, intended for use
166under Unix/Linux, watches the file to see if it has changed since the last emit.
167(A file is deemed to have changed if its device or inode have changed.) If the
168file has changed, the old file stream is closed, and the file opened to get a
169new stream.
170
171This handler is not appropriate for use under Windows, because under Windows
172open log files cannot be moved or renamed - logging opens the files with
173exclusive locks - and so there is no need for such a handler. Furthermore,
Vinay Sajip67f39772013-08-17 00:39:42 +0100174*ST_INO* is not supported under Windows; :func:`~os.stat` always returns zero
175for this value.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000176
177
Vinay Sajipca7b5042019-06-17 17:40:52 +0100178.. class:: WatchedFileHandler(filename, mode='a', encoding=None, delay=False, errors=None)
Vinay Sajipc63619b2010-12-19 12:56:57 +0000179
180 Returns a new instance of the :class:`WatchedFileHandler` class. The specified
181 file is opened and used as the stream for logging. If *mode* is not specified,
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300182 :const:`'a'` is used. If *encoding* is not ``None``, it is used to open the file
Vinay Sajipc63619b2010-12-19 12:56:57 +0000183 with that encoding. If *delay* is true, then file opening is deferred until the
Vinay Sajipca7b5042019-06-17 17:40:52 +0100184 first call to :meth:`emit`. By default, the file grows indefinitely. If
185 *errors* is provided, it determines how encoding errors are handled.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000186
Vinay Sajip638e6222016-07-22 18:23:04 +0100187 .. versionchanged:: 3.6
188 As well as string values, :class:`~pathlib.Path` objects are also accepted
189 for the *filename* argument.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000190
Vinay Sajipca7b5042019-06-17 17:40:52 +0100191 .. versionchanged:: 3.9
192 The *errors* parameter was added.
193
Vinay Sajip29a14452015-10-01 20:54:41 +0100194 .. method:: reopenIfNeeded()
195
196 Checks to see if the file has changed. If it has, the existing stream is
197 flushed and closed and the file opened again, typically as a precursor to
198 outputting the record to the file.
199
Berker Peksag6f038ad2015-10-07 07:54:23 +0300200 .. versionadded:: 3.6
201
Vinay Sajip29a14452015-10-01 20:54:41 +0100202
Vinay Sajipc63619b2010-12-19 12:56:57 +0000203 .. method:: emit(record)
204
Vinay Sajip29a14452015-10-01 20:54:41 +0100205 Outputs the record to the file, but first calls :meth:`reopenIfNeeded` to
206 reopen the file if it has changed.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000207
Vinay Sajip23b94d02012-01-04 12:02:26 +0000208.. _base-rotating-handler:
209
210BaseRotatingHandler
211^^^^^^^^^^^^^^^^^^^
212
213The :class:`BaseRotatingHandler` class, located in the :mod:`logging.handlers`
214module, is the base class for the rotating file handlers,
215:class:`RotatingFileHandler` and :class:`TimedRotatingFileHandler`. You should
216not need to instantiate this class, but it has attributes and methods you may
217need to override.
218
Vinay Sajipca7b5042019-06-17 17:40:52 +0100219.. class:: BaseRotatingHandler(filename, mode, encoding=None, delay=False, errors=None)
Vinay Sajip23b94d02012-01-04 12:02:26 +0000220
221 The parameters are as for :class:`FileHandler`. The attributes are:
222
223 .. attribute:: namer
224
225 If this attribute is set to a callable, the :meth:`rotation_filename`
226 method delegates to this callable. The parameters passed to the callable
227 are those passed to :meth:`rotation_filename`.
228
229 .. note:: The namer function is called quite a few times during rollover,
230 so it should be as simple and as fast as possible. It should also
231 return the same output every time for a given input, otherwise the
232 rollover behaviour may not work as expected.
233
234 .. versionadded:: 3.3
235
236
237 .. attribute:: BaseRotatingHandler.rotator
238
239 If this attribute is set to a callable, the :meth:`rotate` method
240 delegates to this callable. The parameters passed to the callable are
241 those passed to :meth:`rotate`.
242
243 .. versionadded:: 3.3
244
245 .. method:: BaseRotatingHandler.rotation_filename(default_name)
246
247 Modify the filename of a log file when rotating.
248
249 This is provided so that a custom filename can be provided.
250
251 The default implementation calls the 'namer' attribute of the handler,
252 if it's callable, passing the default name to it. If the attribute isn't
Ezio Melotti226231c2012-01-18 05:40:00 +0200253 callable (the default is ``None``), the name is returned unchanged.
Vinay Sajip23b94d02012-01-04 12:02:26 +0000254
255 :param default_name: The default name for the log file.
256
257 .. versionadded:: 3.3
258
259
260 .. method:: BaseRotatingHandler.rotate(source, dest)
261
262 When rotating, rotate the current log.
263
264 The default implementation calls the 'rotator' attribute of the handler,
265 if it's callable, passing the source and dest arguments to it. If the
Ezio Melotti226231c2012-01-18 05:40:00 +0200266 attribute isn't callable (the default is ``None``), the source is simply
Vinay Sajip23b94d02012-01-04 12:02:26 +0000267 renamed to the destination.
268
269 :param source: The source filename. This is normally the base
Martin Panterd21e0b52015-10-10 10:36:22 +0000270 filename, e.g. 'test.log'.
Vinay Sajip23b94d02012-01-04 12:02:26 +0000271 :param dest: The destination filename. This is normally
272 what the source is rotated to, e.g. 'test.log.1'.
273
274 .. versionadded:: 3.3
275
276The reason the attributes exist is to save you having to subclass - you can use
277the same callables for instances of :class:`RotatingFileHandler` and
278:class:`TimedRotatingFileHandler`. If either the namer or rotator callable
279raises an exception, this will be handled in the same way as any other
280exception during an :meth:`emit` call, i.e. via the :meth:`handleError` method
281of the handler.
282
283If you need to make more significant changes to rotation processing, you can
284override the methods.
285
286For an example, see :ref:`cookbook-rotator-namer`.
287
288
Vinay Sajipc63619b2010-12-19 12:56:57 +0000289.. _rotating-file-handler:
290
291RotatingFileHandler
292^^^^^^^^^^^^^^^^^^^
293
294The :class:`RotatingFileHandler` class, located in the :mod:`logging.handlers`
295module, supports rotation of disk log files.
296
297
Vinay Sajipca7b5042019-06-17 17:40:52 +0100298.. class:: RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=False, errors=None)
Vinay Sajipc63619b2010-12-19 12:56:57 +0000299
300 Returns a new instance of the :class:`RotatingFileHandler` class. The specified
301 file is opened and used as the stream for logging. If *mode* is not specified,
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300302 ``'a'`` is used. If *encoding* is not ``None``, it is used to open the file
Vinay Sajipc63619b2010-12-19 12:56:57 +0000303 with that encoding. If *delay* is true, then file opening is deferred until the
Vinay Sajipca7b5042019-06-17 17:40:52 +0100304 first call to :meth:`emit`. By default, the file grows indefinitely. If
305 *errors* is provided, it determines how encoding errors are handled.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000306
307 You can use the *maxBytes* and *backupCount* values to allow the file to
308 :dfn:`rollover` at a predetermined size. When the size is about to be exceeded,
309 the file is closed and a new file is silently opened for output. Rollover occurs
Vinay Sajip53a21eb2016-12-31 11:06:57 +0000310 whenever the current log file is nearly *maxBytes* in length; but if either of
311 *maxBytes* or *backupCount* is zero, rollover never occurs, so you generally want
312 to set *backupCount* to at least 1, and have a non-zero *maxBytes*.
313 When *backupCount* is non-zero, the system will save old log files by appending
314 the extensions '.1', '.2' etc., to the filename. For example, with a *backupCount*
315 of 5 and a base file name of :file:`app.log`, you would get :file:`app.log`,
Vinay Sajipff37cfe2015-01-23 21:19:04 +0000316 :file:`app.log.1`, :file:`app.log.2`, up to :file:`app.log.5`. The file being
317 written to is always :file:`app.log`. When this file is filled, it is closed
318 and renamed to :file:`app.log.1`, and if files :file:`app.log.1`,
Vinay Sajip53a21eb2016-12-31 11:06:57 +0000319 :file:`app.log.2`, etc. exist, then they are renamed to :file:`app.log.2`,
320 :file:`app.log.3` etc. respectively.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000321
Vinay Sajip638e6222016-07-22 18:23:04 +0100322 .. versionchanged:: 3.6
323 As well as string values, :class:`~pathlib.Path` objects are also accepted
324 for the *filename* argument.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000325
Vinay Sajipca7b5042019-06-17 17:40:52 +0100326 .. versionchanged:: 3.9
327 The *errors* parameter was added.
328
Vinay Sajipc63619b2010-12-19 12:56:57 +0000329 .. method:: doRollover()
330
331 Does a rollover, as described above.
332
333
334 .. method:: emit(record)
335
336 Outputs the record to the file, catering for rollover as described
337 previously.
338
339.. _timed-rotating-file-handler:
340
341TimedRotatingFileHandler
342^^^^^^^^^^^^^^^^^^^^^^^^
343
344The :class:`TimedRotatingFileHandler` class, located in the
345:mod:`logging.handlers` module, supports rotation of disk log files at certain
346timed intervals.
347
348
Vinay Sajipca7b5042019-06-17 17:40:52 +0100349.. class:: TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False, atTime=None, errors=None)
Vinay Sajipc63619b2010-12-19 12:56:57 +0000350
351 Returns a new instance of the :class:`TimedRotatingFileHandler` class. The
352 specified file is opened and used as the stream for logging. On rotating it also
353 sets the filename suffix. Rotating happens based on the product of *when* and
354 *interval*.
355
356 You can use the *when* to specify the type of *interval*. The list of possible
357 values is below. Note that they are not case sensitive.
358
Vinay Sajipdd308302016-08-24 17:49:15 +0100359 +----------------+----------------------------+-------------------------+
360 | Value | Type of interval | If/how *atTime* is used |
361 +================+============================+=========================+
362 | ``'S'`` | Seconds | Ignored |
363 +----------------+----------------------------+-------------------------+
364 | ``'M'`` | Minutes | Ignored |
365 +----------------+----------------------------+-------------------------+
366 | ``'H'`` | Hours | Ignored |
367 +----------------+----------------------------+-------------------------+
368 | ``'D'`` | Days | Ignored |
369 +----------------+----------------------------+-------------------------+
370 | ``'W0'-'W6'`` | Weekday (0=Monday) | Used to compute initial |
371 | | | rollover time |
372 +----------------+----------------------------+-------------------------+
373 | ``'midnight'`` | Roll over at midnight, if | Used to compute initial |
374 | | *atTime* not specified, | rollover time |
375 | | else at time *atTime* | |
376 +----------------+----------------------------+-------------------------+
Vinay Sajipc63619b2010-12-19 12:56:57 +0000377
Vinay Sajip832d99b2013-03-08 23:24:30 +0000378 When using weekday-based rotation, specify 'W0' for Monday, 'W1' for
379 Tuesday, and so on up to 'W6' for Sunday. In this case, the value passed for
380 *interval* isn't used.
381
Vinay Sajipc63619b2010-12-19 12:56:57 +0000382 The system will save old log files by appending extensions to the filename.
383 The extensions are date-and-time based, using the strftime format
384 ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on the
385 rollover interval.
386
387 When computing the next rollover time for the first time (when the handler
388 is created), the last modification time of an existing log file, or else
389 the current time, is used to compute when the next rotation will occur.
390
391 If the *utc* argument is true, times in UTC will be used; otherwise
392 local time is used.
393
394 If *backupCount* is nonzero, at most *backupCount* files
395 will be kept, and if more would be created when rollover occurs, the oldest
396 one is deleted. The deletion logic uses the interval to determine which
397 files to delete, so changing the interval may leave old files lying around.
398
399 If *delay* is true, then file opening is deferred until the first call to
400 :meth:`emit`.
401
Vinay Sajipa7130792013-04-12 17:04:23 +0100402 If *atTime* is not ``None``, it must be a ``datetime.time`` instance which
403 specifies the time of day when rollover occurs, for the cases where rollover
Vinay Sajipdd308302016-08-24 17:49:15 +0100404 is set to happen "at midnight" or "on a particular weekday". Note that in
405 these cases, the *atTime* value is effectively used to compute the *initial*
406 rollover, and subsequent rollovers would be calculated via the normal
407 interval calculation.
408
Vinay Sajipca7b5042019-06-17 17:40:52 +0100409 If *errors* is specified, it's used to determine how encoding errors are
410 handled.
411
Vinay Sajipdd308302016-08-24 17:49:15 +0100412 .. note:: Calculation of the initial rollover time is done when the handler
413 is initialised. Calculation of subsequent rollover times is done only
414 when rollover occurs, and rollover occurs only when emitting output. If
415 this is not kept in mind, it might lead to some confusion. For example,
416 if an interval of "every minute" is set, that does not mean you will
417 always see log files with times (in the filename) separated by a minute;
418 if, during application execution, logging output is generated more
419 frequently than once a minute, *then* you can expect to see log files
420 with times separated by a minute. If, on the other hand, logging messages
421 are only output once every five minutes (say), then there will be gaps in
422 the file times corresponding to the minutes where no output (and hence no
423 rollover) occurred.
Vinay Sajipa7130792013-04-12 17:04:23 +0100424
425 .. versionchanged:: 3.4
426 *atTime* parameter was added.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000427
Vinay Sajip638e6222016-07-22 18:23:04 +0100428 .. versionchanged:: 3.6
429 As well as string values, :class:`~pathlib.Path` objects are also accepted
430 for the *filename* argument.
431
Vinay Sajipca7b5042019-06-17 17:40:52 +0100432 .. versionchanged:: 3.9
433 The *errors* parameter was added.
434
Vinay Sajipc63619b2010-12-19 12:56:57 +0000435 .. method:: doRollover()
436
437 Does a rollover, as described above.
438
Vinay Sajipc63619b2010-12-19 12:56:57 +0000439 .. method:: emit(record)
440
441 Outputs the record to the file, catering for rollover as described above.
442
443
444.. _socket-handler:
445
446SocketHandler
447^^^^^^^^^^^^^
448
449The :class:`SocketHandler` class, located in the :mod:`logging.handlers` module,
450sends logging output to a network socket. The base class uses a TCP socket.
451
452
453.. class:: SocketHandler(host, port)
454
455 Returns a new instance of the :class:`SocketHandler` class intended to
456 communicate with a remote machine whose address is given by *host* and *port*.
457
Vinay Sajip5421f352013-09-27 18:18:28 +0100458 .. versionchanged:: 3.4
459 If ``port`` is specified as ``None``, a Unix domain socket is created
460 using the value in ``host`` - otherwise, a TCP socket is created.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000461
462 .. method:: close()
463
464 Closes the socket.
465
466
467 .. method:: emit()
468
469 Pickles the record's attribute dictionary and writes it to the socket in
470 binary format. If there is an error with the socket, silently drops the
471 packet. If the connection was previously lost, re-establishes the
472 connection. To unpickle the record at the receiving end into a
Vinay Sajip67f39772013-08-17 00:39:42 +0100473 :class:`~logging.LogRecord`, use the :func:`~logging.makeLogRecord`
474 function.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000475
476
477 .. method:: handleError()
478
479 Handles an error which has occurred during :meth:`emit`. The most likely
480 cause is a lost connection. Closes the socket so that we can retry on the
481 next event.
482
483
484 .. method:: makeSocket()
485
486 This is a factory method which allows subclasses to define the precise
487 type of socket they want. The default implementation creates a TCP socket
488 (:const:`socket.SOCK_STREAM`).
489
490
491 .. method:: makePickle(record)
492
493 Pickles the record's attribute dictionary in binary format with a length
Vinay Sajipf06b5692019-06-19 15:29:57 +0100494 prefix, and returns it ready for transmission across the socket. The
495 details of this operation are equivalent to::
496
497 data = pickle.dumps(record_attr_dict, 1)
498 datalen = struct.pack('>L', len(data))
499 return datalen + data
Vinay Sajipc63619b2010-12-19 12:56:57 +0000500
501 Note that pickles aren't completely secure. If you are concerned about
502 security, you may want to override this method to implement a more secure
503 mechanism. For example, you can sign pickles using HMAC and then verify
504 them on the receiving end, or alternatively you can disable unpickling of
505 global objects on the receiving end.
506
Georg Brandl08e278a2011-02-15 12:44:43 +0000507
Vinay Sajipc63619b2010-12-19 12:56:57 +0000508 .. method:: send(packet)
509
Vinay Sajipf06b5692019-06-19 15:29:57 +0100510 Send a pickled byte-string *packet* to the socket. The format of the sent
511 byte-string is as described in the documentation for
512 :meth:`~SocketHandler.makePickle`.
513
514 This function allows for partial sends, which can happen when the network
515 is busy.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000516
Georg Brandl08e278a2011-02-15 12:44:43 +0000517
Georg Brandldbb95852011-02-15 12:41:17 +0000518 .. method:: createSocket()
519
520 Tries to create a socket; on failure, uses an exponential back-off
Donald Stufft8b852f12014-05-20 12:58:38 -0400521 algorithm. On initial failure, the handler will drop the message it was
Georg Brandldbb95852011-02-15 12:41:17 +0000522 trying to send. When subsequent messages are handled by the same
523 instance, it will not try connecting until some time has passed. The
524 default parameters are such that the initial delay is one second, and if
525 after that delay the connection still can't be made, the handler will
526 double the delay each time up to a maximum of 30 seconds.
527
528 This behaviour is controlled by the following handler attributes:
529
530 * ``retryStart`` (initial delay, defaulting to 1.0 seconds).
531 * ``retryFactor`` (multiplier, defaulting to 2.0).
532 * ``retryMax`` (maximum delay, defaulting to 30.0 seconds).
533
534 This means that if the remote listener starts up *after* the handler has
535 been used, you could lose messages (since the handler won't even attempt
536 a connection until the delay has elapsed, but just silently drop messages
537 during the delay period).
Georg Brandl08e278a2011-02-15 12:44:43 +0000538
Vinay Sajipc63619b2010-12-19 12:56:57 +0000539
540.. _datagram-handler:
541
542DatagramHandler
543^^^^^^^^^^^^^^^
544
545The :class:`DatagramHandler` class, located in the :mod:`logging.handlers`
546module, inherits from :class:`SocketHandler` to support sending logging messages
547over UDP sockets.
548
549
550.. class:: DatagramHandler(host, port)
551
552 Returns a new instance of the :class:`DatagramHandler` class intended to
553 communicate with a remote machine whose address is given by *host* and *port*.
554
Vinay Sajip5421f352013-09-27 18:18:28 +0100555 .. versionchanged:: 3.4
556 If ``port`` is specified as ``None``, a Unix domain socket is created
Mike DePalatis233de022018-03-30 03:36:06 -0400557 using the value in ``host`` - otherwise, a UDP socket is created.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000558
559 .. method:: emit()
560
561 Pickles the record's attribute dictionary and writes it to the socket in
562 binary format. If there is an error with the socket, silently drops the
563 packet. To unpickle the record at the receiving end into a
Vinay Sajip67f39772013-08-17 00:39:42 +0100564 :class:`~logging.LogRecord`, use the :func:`~logging.makeLogRecord`
565 function.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000566
567
568 .. method:: makeSocket()
569
570 The factory method of :class:`SocketHandler` is here overridden to create
571 a UDP socket (:const:`socket.SOCK_DGRAM`).
572
573
574 .. method:: send(s)
575
Vinay Sajipf06b5692019-06-19 15:29:57 +0100576 Send a pickled byte-string to a socket. The format of the sent byte-string
577 is as described in the documentation for :meth:`SocketHandler.makePickle`.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000578
579
580.. _syslog-handler:
581
582SysLogHandler
583^^^^^^^^^^^^^
584
585The :class:`SysLogHandler` class, located in the :mod:`logging.handlers` module,
586supports sending logging messages to a remote or local Unix syslog.
587
588
589.. class:: SysLogHandler(address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER, socktype=socket.SOCK_DGRAM)
590
591 Returns a new instance of the :class:`SysLogHandler` class intended to
592 communicate with a remote Unix machine whose address is given by *address* in
593 the form of a ``(host, port)`` tuple. If *address* is not specified,
594 ``('localhost', 514)`` is used. The address is used to open a socket. An
595 alternative to providing a ``(host, port)`` tuple is providing an address as a
596 string, for example '/dev/log'. In this case, a Unix domain socket is used to
597 send the message to the syslog. If *facility* is not specified,
598 :const:`LOG_USER` is used. The type of socket opened depends on the
599 *socktype* argument, which defaults to :const:`socket.SOCK_DGRAM` and thus
600 opens a UDP socket. To open a TCP socket (for use with the newer syslog
601 daemons such as rsyslog), specify a value of :const:`socket.SOCK_STREAM`.
602
603 Note that if your server is not listening on UDP port 514,
604 :class:`SysLogHandler` may appear not to work. In that case, check what
605 address you should be using for a domain socket - it's system dependent.
606 For example, on Linux it's usually '/dev/log' but on OS/X it's
607 '/var/run/syslog'. You'll need to check your platform and use the
608 appropriate address (you may need to do this check at runtime if your
609 application needs to run on several platforms). On Windows, you pretty
610 much have to use the UDP option.
611
612 .. versionchanged:: 3.2
613 *socktype* was added.
614
615
616 .. method:: close()
617
618 Closes the socket to the remote host.
619
620
621 .. method:: emit(record)
622
623 The record is formatted, and then sent to the syslog server. If exception
624 information is present, it is *not* sent to the server.
625
Vinay Sajip645e4582011-06-10 18:52:50 +0100626 .. versionchanged:: 3.2.1
627 (See: :issue:`12168`.) In earlier versions, the message sent to the
628 syslog daemons was always terminated with a NUL byte, because early
629 versions of these daemons expected a NUL terminated message - even
Serhiy Storchaka0a36ac12018-05-31 07:39:00 +0300630 though it's not in the relevant specification (:rfc:`5424`). More recent
Vinay Sajip645e4582011-06-10 18:52:50 +0100631 versions of these daemons don't expect the NUL byte but strip it off
632 if it's there, and even more recent daemons (which adhere more closely
633 to RFC 5424) pass the NUL byte on as part of the message.
634
635 To enable easier handling of syslog messages in the face of all these
636 differing daemon behaviours, the appending of the NUL byte has been
637 made configurable, through the use of a class-level attribute,
638 ``append_nul``. This defaults to ``True`` (preserving the existing
639 behaviour) but can be set to ``False`` on a ``SysLogHandler`` instance
640 in order for that instance to *not* append the NUL terminator.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000641
Vinay Sajip2353e352011-06-27 15:40:06 +0100642 .. versionchanged:: 3.3
643 (See: :issue:`12419`.) In earlier versions, there was no facility for
644 an "ident" or "tag" prefix to identify the source of the message. This
645 can now be specified using a class-level attribute, defaulting to
646 ``""`` to preserve existing behaviour, but which can be overridden on
647 a ``SysLogHandler`` instance in order for that instance to prepend
648 the ident to every message handled. Note that the provided ident must
649 be text, not bytes, and is prepended to the message exactly as is.
650
Vinay Sajipc63619b2010-12-19 12:56:57 +0000651 .. method:: encodePriority(facility, priority)
652
653 Encodes the facility and priority into an integer. You can pass in strings
654 or integers - if strings are passed, internal mapping dictionaries are
655 used to convert them to integers.
656
657 The symbolic ``LOG_`` values are defined in :class:`SysLogHandler` and
658 mirror the values defined in the ``sys/syslog.h`` header file.
659
660 **Priorities**
661
662 +--------------------------+---------------+
663 | Name (string) | Symbolic value|
664 +==========================+===============+
665 | ``alert`` | LOG_ALERT |
666 +--------------------------+---------------+
667 | ``crit`` or ``critical`` | LOG_CRIT |
668 +--------------------------+---------------+
669 | ``debug`` | LOG_DEBUG |
670 +--------------------------+---------------+
671 | ``emerg`` or ``panic`` | LOG_EMERG |
672 +--------------------------+---------------+
673 | ``err`` or ``error`` | LOG_ERR |
674 +--------------------------+---------------+
675 | ``info`` | LOG_INFO |
676 +--------------------------+---------------+
677 | ``notice`` | LOG_NOTICE |
678 +--------------------------+---------------+
679 | ``warn`` or ``warning`` | LOG_WARNING |
680 +--------------------------+---------------+
681
682 **Facilities**
683
684 +---------------+---------------+
685 | Name (string) | Symbolic value|
686 +===============+===============+
687 | ``auth`` | LOG_AUTH |
688 +---------------+---------------+
689 | ``authpriv`` | LOG_AUTHPRIV |
690 +---------------+---------------+
691 | ``cron`` | LOG_CRON |
692 +---------------+---------------+
693 | ``daemon`` | LOG_DAEMON |
694 +---------------+---------------+
695 | ``ftp`` | LOG_FTP |
696 +---------------+---------------+
697 | ``kern`` | LOG_KERN |
698 +---------------+---------------+
699 | ``lpr`` | LOG_LPR |
700 +---------------+---------------+
701 | ``mail`` | LOG_MAIL |
702 +---------------+---------------+
703 | ``news`` | LOG_NEWS |
704 +---------------+---------------+
705 | ``syslog`` | LOG_SYSLOG |
706 +---------------+---------------+
707 | ``user`` | LOG_USER |
708 +---------------+---------------+
709 | ``uucp`` | LOG_UUCP |
710 +---------------+---------------+
711 | ``local0`` | LOG_LOCAL0 |
712 +---------------+---------------+
713 | ``local1`` | LOG_LOCAL1 |
714 +---------------+---------------+
715 | ``local2`` | LOG_LOCAL2 |
716 +---------------+---------------+
717 | ``local3`` | LOG_LOCAL3 |
718 +---------------+---------------+
719 | ``local4`` | LOG_LOCAL4 |
720 +---------------+---------------+
721 | ``local5`` | LOG_LOCAL5 |
722 +---------------+---------------+
723 | ``local6`` | LOG_LOCAL6 |
724 +---------------+---------------+
725 | ``local7`` | LOG_LOCAL7 |
726 +---------------+---------------+
727
728 .. method:: mapPriority(levelname)
729
730 Maps a logging level name to a syslog priority name.
731 You may need to override this if you are using custom levels, or
732 if the default algorithm is not suitable for your needs. The
733 default algorithm maps ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and
734 ``CRITICAL`` to the equivalent syslog names, and all other level
735 names to 'warning'.
736
737.. _nt-eventlog-handler:
738
739NTEventLogHandler
740^^^^^^^^^^^^^^^^^
741
742The :class:`NTEventLogHandler` class, located in the :mod:`logging.handlers`
743module, supports sending logging messages to a local Windows NT, Windows 2000 or
744Windows XP event log. Before you can use it, you need Mark Hammond's Win32
745extensions for Python installed.
746
747
748.. class:: NTEventLogHandler(appname, dllname=None, logtype='Application')
749
750 Returns a new instance of the :class:`NTEventLogHandler` class. The *appname* is
751 used to define the application name as it appears in the event log. An
752 appropriate registry entry is created using this name. The *dllname* should give
753 the fully qualified pathname of a .dll or .exe which contains message
754 definitions to hold in the log (if not specified, ``'win32service.pyd'`` is used
755 - this is installed with the Win32 extensions and contains some basic
756 placeholder message definitions. Note that use of these placeholders will make
757 your event logs big, as the entire message source is held in the log. If you
758 want slimmer logs, you have to pass in the name of your own .dll or .exe which
759 contains the message definitions you want to use in the event log). The
760 *logtype* is one of ``'Application'``, ``'System'`` or ``'Security'``, and
761 defaults to ``'Application'``.
762
763
764 .. method:: close()
765
766 At this point, you can remove the application name from the registry as a
767 source of event log entries. However, if you do this, you will not be able
768 to see the events as you intended in the Event Log Viewer - it needs to be
769 able to access the registry to get the .dll name. The current version does
770 not do this.
771
772
773 .. method:: emit(record)
774
775 Determines the message ID, event category and event type, and then logs
776 the message in the NT event log.
777
778
779 .. method:: getEventCategory(record)
780
781 Returns the event category for the record. Override this if you want to
782 specify your own categories. This version returns 0.
783
784
785 .. method:: getEventType(record)
786
787 Returns the event type for the record. Override this if you want to
788 specify your own types. This version does a mapping using the handler's
789 typemap attribute, which is set up in :meth:`__init__` to a dictionary
790 which contains mappings for :const:`DEBUG`, :const:`INFO`,
791 :const:`WARNING`, :const:`ERROR` and :const:`CRITICAL`. If you are using
792 your own levels, you will either need to override this method or place a
793 suitable dictionary in the handler's *typemap* attribute.
794
795
796 .. method:: getMessageID(record)
797
798 Returns the message ID for the record. If you are using your own messages,
799 you could do this by having the *msg* passed to the logger being an ID
800 rather than a format string. Then, in here, you could use a dictionary
801 lookup to get the message ID. This version returns 1, which is the base
802 message ID in :file:`win32service.pyd`.
803
804.. _smtp-handler:
805
806SMTPHandler
807^^^^^^^^^^^
808
809The :class:`SMTPHandler` class, located in the :mod:`logging.handlers` module,
810supports sending logging messages to an email address via SMTP.
811
812
Vinay Sajip38a12af2012-03-26 17:17:39 +0100813.. class:: SMTPHandler(mailhost, fromaddr, toaddrs, subject, credentials=None, secure=None, timeout=1.0)
Vinay Sajipc63619b2010-12-19 12:56:57 +0000814
815 Returns a new instance of the :class:`SMTPHandler` class. The instance is
816 initialized with the from and to addresses and subject line of the email. The
817 *toaddrs* should be a list of strings. To specify a non-standard SMTP port, use
818 the (host, port) tuple format for the *mailhost* argument. If you use a string,
819 the standard SMTP port is used. If your SMTP server requires authentication, you
820 can specify a (username, password) tuple for the *credentials* argument.
821
Vinay Sajip95259562011-08-01 11:31:52 +0100822 To specify the use of a secure protocol (TLS), pass in a tuple to the
823 *secure* argument. This will only be used when authentication credentials are
824 supplied. The tuple should be either an empty tuple, or a single-value tuple
825 with the name of a keyfile, or a 2-value tuple with the names of the keyfile
826 and certificate file. (This tuple is passed to the
827 :meth:`smtplib.SMTP.starttls` method.)
Vinay Sajipc63619b2010-12-19 12:56:57 +0000828
Vinay Sajip38a12af2012-03-26 17:17:39 +0100829 A timeout can be specified for communication with the SMTP server using the
830 *timeout* argument.
831
832 .. versionadded:: 3.3
833 The *timeout* argument was added.
834
Vinay Sajipc63619b2010-12-19 12:56:57 +0000835 .. method:: emit(record)
836
837 Formats the record and sends it to the specified addressees.
838
839
840 .. method:: getSubject(record)
841
842 If you want to specify a subject line which is record-dependent, override
843 this method.
844
845.. _memory-handler:
846
847MemoryHandler
848^^^^^^^^^^^^^
849
850The :class:`MemoryHandler` class, located in the :mod:`logging.handlers` module,
851supports buffering of logging records in memory, periodically flushing them to a
852:dfn:`target` handler. Flushing occurs whenever the buffer is full, or when an
853event of a certain severity or greater is seen.
854
855:class:`MemoryHandler` is a subclass of the more general
856:class:`BufferingHandler`, which is an abstract class. This buffers logging
857records in memory. Whenever each record is added to the buffer, a check is made
858by calling :meth:`shouldFlush` to see if the buffer should be flushed. If it
Vinay Sajip8ece80f2012-03-26 17:09:58 +0100859should, then :meth:`flush` is expected to do the flushing.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000860
861
862.. class:: BufferingHandler(capacity)
863
Vinay Sajip84de34e2019-07-01 12:41:21 +0100864 Initializes the handler with a buffer of the specified capacity. Here,
865 *capacity* means the number of logging records buffered.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000866
867
868 .. method:: emit(record)
869
870 Appends the record to the buffer. If :meth:`shouldFlush` returns true,
871 calls :meth:`flush` to process the buffer.
872
873
874 .. method:: flush()
875
876 You can override this to implement custom flushing behavior. This version
877 just zaps the buffer to empty.
878
879
880 .. method:: shouldFlush(record)
881
882 Returns true if the buffer is up to capacity. This method can be
883 overridden to implement custom flushing strategies.
884
885
Vinay Sajipcccf6062016-07-22 16:27:31 +0100886.. class:: MemoryHandler(capacity, flushLevel=ERROR, target=None, flushOnClose=True)
Vinay Sajipc63619b2010-12-19 12:56:57 +0000887
888 Returns a new instance of the :class:`MemoryHandler` class. The instance is
Vinay Sajip84de34e2019-07-01 12:41:21 +0100889 initialized with a buffer size of *capacity* (number of records buffered).
890 If *flushLevel* is not specified, :const:`ERROR` is used. If no *target* is
891 specified, the target will need to be set using :meth:`setTarget` before this
892 handler does anything useful. If *flushOnClose* is specified as ``False``,
893 then the buffer is *not* flushed when the handler is closed. If not specified
894 or specified as ``True``, the previous behaviour of flushing the buffer will
895 occur when the handler is closed.
Vinay Sajipcccf6062016-07-22 16:27:31 +0100896
897 .. versionchanged:: 3.6
898 The *flushOnClose* parameter was added.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000899
900
901 .. method:: close()
902
Ezio Melotti226231c2012-01-18 05:40:00 +0200903 Calls :meth:`flush`, sets the target to ``None`` and clears the
Vinay Sajipc63619b2010-12-19 12:56:57 +0000904 buffer.
905
906
907 .. method:: flush()
908
909 For a :class:`MemoryHandler`, flushing means just sending the buffered
910 records to the target, if there is one. The buffer is also cleared when
911 this happens. Override if you want different behavior.
912
913
914 .. method:: setTarget(target)
915
916 Sets the target handler for this handler.
917
918
919 .. method:: shouldFlush(record)
920
921 Checks for buffer full or a record at the *flushLevel* or higher.
922
923
924.. _http-handler:
925
926HTTPHandler
927^^^^^^^^^^^
928
929The :class:`HTTPHandler` class, located in the :mod:`logging.handlers` module,
930supports sending logging messages to a Web server, using either ``GET`` or
931``POST`` semantics.
932
933
Benjamin Peterson43052a12014-11-23 20:36:44 -0600934.. class:: HTTPHandler(host, url, method='GET', secure=False, credentials=None, context=None)
Vinay Sajipc63619b2010-12-19 12:56:57 +0000935
936 Returns a new instance of the :class:`HTTPHandler` class. The *host* can be
Benjamin Peterson43052a12014-11-23 20:36:44 -0600937 of the form ``host:port``, should you need to use a specific port number. If
938 no *method* is specified, ``GET`` is used. If *secure* is true, a HTTPS
939 connection will be used. The *context* parameter may be set to a
940 :class:`ssl.SSLContext` instance to configure the SSL settings used for the
941 HTTPS connection. If *credentials* is specified, it should be a 2-tuple
942 consisting of userid and password, which will be placed in a HTTP
Vinay Sajipc63619b2010-12-19 12:56:57 +0000943 'Authorization' header using Basic authentication. If you specify
944 credentials, you should also specify secure=True so that your userid and
945 password are not passed in cleartext across the wire.
946
Benjamin Petersona90e92d2014-11-23 20:38:37 -0600947 .. versionchanged:: 3.5
Benjamin Peterson43052a12014-11-23 20:36:44 -0600948 The *context* parameter was added.
949
Vinay Sajipc673a9a2014-05-30 18:59:27 +0100950 .. method:: mapLogRecord(record)
951
952 Provides a dictionary, based on ``record``, which is to be URL-encoded
953 and sent to the web server. The default implementation just returns
954 ``record.__dict__``. This method can be overridden if e.g. only a
955 subset of :class:`~logging.LogRecord` is to be sent to the web server, or
956 if more specific customization of what's sent to the server is required.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000957
958 .. method:: emit(record)
959
Martin Panter6245cb32016-04-15 02:14:19 +0000960 Sends the record to the Web server as a URL-encoded dictionary. The
Vinay Sajipc673a9a2014-05-30 18:59:27 +0100961 :meth:`mapLogRecord` method is used to convert the record to the
962 dictionary to be sent.
963
Berker Peksag9c1dba22014-09-28 00:00:58 +0300964 .. note:: Since preparing a record for sending it to a Web server is not
Vinay Sajipc673a9a2014-05-30 18:59:27 +0100965 the same as a generic formatting operation, using
966 :meth:`~logging.Handler.setFormatter` to specify a
967 :class:`~logging.Formatter` for a :class:`HTTPHandler` has no effect.
968 Instead of calling :meth:`~logging.Handler.format`, this handler calls
969 :meth:`mapLogRecord` and then :func:`urllib.parse.urlencode` to encode the
970 dictionary in a form suitable for sending to a Web server.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000971
972
973.. _queue-handler:
974
975
976QueueHandler
977^^^^^^^^^^^^
978
979.. versionadded:: 3.2
980
981The :class:`QueueHandler` class, located in the :mod:`logging.handlers` module,
982supports sending logging messages to a queue, such as those implemented in the
983:mod:`queue` or :mod:`multiprocessing` modules.
984
985Along with the :class:`QueueListener` class, :class:`QueueHandler` can be used
986to let handlers do their work on a separate thread from the one which does the
987logging. This is important in Web applications and also other service
988applications where threads servicing clients need to respond as quickly as
989possible, while any potentially slow operations (such as sending an email via
990:class:`SMTPHandler`) are done on a separate thread.
991
992.. class:: QueueHandler(queue)
993
994 Returns a new instance of the :class:`QueueHandler` class. The instance is
Vinay Sajipe6b64b72019-07-01 18:45:07 +0100995 initialized with the queue to send messages to. The *queue* can be any
996 queue-like object; it's used as-is by the :meth:`enqueue` method, which
997 needs to know how to send messages to it. The queue is not *required* to
998 have the task tracking API, which means that you can use
999 :class:`~queue.SimpleQueue` instances for *queue*.
Vinay Sajipc63619b2010-12-19 12:56:57 +00001000
1001
1002 .. method:: emit(record)
1003
Vinay Sajip0f4e8132019-07-01 20:45:01 +01001004 Enqueues the result of preparing the LogRecord. Should an exception
1005 occur (e.g. because a bounded queue has filled up), the
1006 :meth:`~logging.Handler.handleError` method is called to handle the
1007 error. This can result in the record silently being dropped (if
1008 :attr:`logging.raiseExceptions` is ``False``) or a message printed to
1009 ``sys.stderr`` (if :attr:`logging.raiseExceptions` is ``True``).
Vinay Sajipc63619b2010-12-19 12:56:57 +00001010
1011 .. method:: prepare(record)
1012
1013 Prepares a record for queuing. The object returned by this
1014 method is enqueued.
1015
Cheryl Sabellad345bb42018-09-25 19:00:08 -04001016 The base implementation formats the record to merge the message,
1017 arguments, and exception information, if present. It also
1018 removes unpickleable items from the record in-place.
Vinay Sajipc63619b2010-12-19 12:56:57 +00001019
1020 You might want to override this method if you want to convert
1021 the record to a dict or JSON string, or send a modified copy
1022 of the record while leaving the original intact.
1023
1024 .. method:: enqueue(record)
1025
1026 Enqueues the record on the queue using ``put_nowait()``; you may
1027 want to override this if you want to use blocking behaviour, or a
Vinay Sajip9c10d6b2013-11-15 20:58:13 +00001028 timeout, or a customized queue implementation.
Vinay Sajipc63619b2010-12-19 12:56:57 +00001029
1030
1031
Éric Araujo5eada942011-08-19 00:41:23 +02001032.. _queue-listener:
Vinay Sajipc63619b2010-12-19 12:56:57 +00001033
1034QueueListener
1035^^^^^^^^^^^^^
1036
1037.. versionadded:: 3.2
1038
1039The :class:`QueueListener` class, located in the :mod:`logging.handlers`
1040module, supports receiving logging messages from a queue, such as those
1041implemented in the :mod:`queue` or :mod:`multiprocessing` modules. The
1042messages are received from a queue in an internal thread and passed, on
1043the same thread, to one or more handlers for processing. While
1044:class:`QueueListener` is not itself a handler, it is documented here
1045because it works hand-in-hand with :class:`QueueHandler`.
1046
1047Along with the :class:`QueueHandler` class, :class:`QueueListener` can be used
1048to let handlers do their work on a separate thread from the one which does the
1049logging. This is important in Web applications and also other service
1050applications where threads servicing clients need to respond as quickly as
1051possible, while any potentially slow operations (such as sending an email via
1052:class:`SMTPHandler`) are done on a separate thread.
1053
Vinay Sajip365701a2015-02-09 19:49:00 +00001054.. class:: QueueListener(queue, *handlers, respect_handler_level=False)
Vinay Sajipc63619b2010-12-19 12:56:57 +00001055
1056 Returns a new instance of the :class:`QueueListener` class. The instance is
1057 initialized with the queue to send messages to and a list of handlers which
Martin Panter8f137832017-01-14 08:24:20 +00001058 will handle entries placed on the queue. The queue can be any queue-like
1059 object; it's passed as-is to the :meth:`dequeue` method, which needs
Vinay Sajipe6b64b72019-07-01 18:45:07 +01001060 to know how to get messages from it. The queue is not *required* to have the
1061 task tracking API (though it's used if available), which means that you can
1062 use :class:`~queue.SimpleQueue` instances for *queue*.
1063
1064 If ``respect_handler_level`` is ``True``, a handler's level is respected
1065 (compared with the level for the message) when deciding whether to pass
1066 messages to that handler; otherwise, the behaviour is as in previous Python
1067 versions - to always pass each message to each handler.
Vinay Sajip365701a2015-02-09 19:49:00 +00001068
1069 .. versionchanged:: 3.5
wwuckefd57412019-09-11 16:44:37 +10001070 The ``respect_handler_level`` argument was added.
Vinay Sajipc63619b2010-12-19 12:56:57 +00001071
1072 .. method:: dequeue(block)
1073
1074 Dequeues a record and return it, optionally blocking.
1075
1076 The base implementation uses ``get()``. You may want to override this
1077 method if you want to use timeouts or work with custom queue
1078 implementations.
1079
1080 .. method:: prepare(record)
1081
1082 Prepare a record for handling.
1083
1084 This implementation just returns the passed-in record. You may want to
1085 override this method if you need to do any custom marshalling or
1086 manipulation of the record before passing it to the handlers.
1087
1088 .. method:: handle(record)
1089
1090 Handle a record.
1091
1092 This just loops through the handlers offering them the record
1093 to handle. The actual object passed to the handlers is that which
1094 is returned from :meth:`prepare`.
1095
1096 .. method:: start()
1097
1098 Starts the listener.
1099
1100 This starts up a background thread to monitor the queue for
1101 LogRecords to process.
1102
1103 .. method:: stop()
1104
1105 Stops the listener.
1106
1107 This asks the thread to terminate, and then waits for it to do so.
1108 Note that if you don't call this before your application exits, there
1109 may be some records still left on the queue, which won't be processed.
1110
Vinay Sajipa29a9dd2011-02-25 16:05:26 +00001111 .. method:: enqueue_sentinel()
1112
1113 Writes a sentinel to the queue to tell the listener to quit. This
1114 implementation uses ``put_nowait()``. You may want to override this
1115 method if you want to use timeouts or work with custom queue
1116 implementations.
1117
1118 .. versionadded:: 3.3
1119
Vinay Sajipc63619b2010-12-19 12:56:57 +00001120
1121.. seealso::
1122
1123 Module :mod:`logging`
1124 API reference for the logging module.
1125
1126 Module :mod:`logging.config`
1127 Configuration API for the logging module.
1128
1129