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