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