Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1 | :mod:`logging` --- Logging facility for Python |
| 2 | ============================================== |
| 3 | |
| 4 | .. module:: logging |
| 5 | :synopsis: Flexible error logging system for applications. |
| 6 | |
| 7 | |
| 8 | .. moduleauthor:: Vinay Sajip <vinay_sajip@red-dove.com> |
| 9 | .. sectionauthor:: Vinay Sajip <vinay_sajip@red-dove.com> |
| 10 | |
| 11 | |
| 12 | .. % These apply to all modules, and may be given more than once: |
| 13 | |
| 14 | |
| 15 | |
| 16 | .. index:: pair: Errors; logging |
| 17 | |
| 18 | .. versionadded:: 2.3 |
| 19 | |
| 20 | This module defines functions and classes which implement a flexible error |
| 21 | logging system for applications. |
| 22 | |
| 23 | Logging is performed by calling methods on instances of the :class:`Logger` |
| 24 | class (hereafter called :dfn:`loggers`). Each instance has a name, and they are |
Georg Brandl | a739503 | 2007-10-21 12:15:05 +0000 | [diff] [blame^] | 25 | conceptually arranged in a namespace hierarchy using dots (periods) as |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 26 | separators. For example, a logger named "scan" is the parent of loggers |
| 27 | "scan.text", "scan.html" and "scan.pdf". Logger names can be anything you want, |
| 28 | and indicate the area of an application in which a logged message originates. |
| 29 | |
| 30 | Logged messages also have levels of importance associated with them. The default |
| 31 | levels provided are :const:`DEBUG`, :const:`INFO`, :const:`WARNING`, |
| 32 | :const:`ERROR` and :const:`CRITICAL`. As a convenience, you indicate the |
| 33 | importance of a logged message by calling an appropriate method of |
| 34 | :class:`Logger`. The methods are :meth:`debug`, :meth:`info`, :meth:`warning`, |
| 35 | :meth:`error` and :meth:`critical`, which mirror the default levels. You are not |
| 36 | constrained to use these levels: you can specify your own and use a more general |
| 37 | :class:`Logger` method, :meth:`log`, which takes an explicit level argument. |
| 38 | |
| 39 | The numeric values of logging levels are given in the following table. These are |
| 40 | primarily of interest if you want to define your own levels, and need them to |
| 41 | have specific values relative to the predefined levels. If you define a level |
| 42 | with the same numeric value, it overwrites the predefined value; the predefined |
| 43 | name is lost. |
| 44 | |
| 45 | +--------------+---------------+ |
| 46 | | Level | Numeric value | |
| 47 | +==============+===============+ |
| 48 | | ``CRITICAL`` | 50 | |
| 49 | +--------------+---------------+ |
| 50 | | ``ERROR`` | 40 | |
| 51 | +--------------+---------------+ |
| 52 | | ``WARNING`` | 30 | |
| 53 | +--------------+---------------+ |
| 54 | | ``INFO`` | 20 | |
| 55 | +--------------+---------------+ |
| 56 | | ``DEBUG`` | 10 | |
| 57 | +--------------+---------------+ |
| 58 | | ``NOTSET`` | 0 | |
| 59 | +--------------+---------------+ |
| 60 | |
| 61 | Levels can also be associated with loggers, being set either by the developer or |
| 62 | through loading a saved logging configuration. When a logging method is called |
| 63 | on a logger, the logger compares its own level with the level associated with |
| 64 | the method call. If the logger's level is higher than the method call's, no |
| 65 | logging message is actually generated. This is the basic mechanism controlling |
| 66 | the verbosity of logging output. |
| 67 | |
| 68 | Logging messages are encoded as instances of the :class:`LogRecord` class. When |
| 69 | a logger decides to actually log an event, a :class:`LogRecord` instance is |
| 70 | created from the logging message. |
| 71 | |
| 72 | Logging messages are subjected to a dispatch mechanism through the use of |
| 73 | :dfn:`handlers`, which are instances of subclasses of the :class:`Handler` |
| 74 | class. Handlers are responsible for ensuring that a logged message (in the form |
| 75 | of a :class:`LogRecord`) ends up in a particular location (or set of locations) |
| 76 | which is useful for the target audience for that message (such as end users, |
| 77 | support desk staff, system administrators, developers). Handlers are passed |
| 78 | :class:`LogRecord` instances intended for particular destinations. Each logger |
| 79 | can have zero, one or more handlers associated with it (via the |
| 80 | :meth:`addHandler` method of :class:`Logger`). In addition to any handlers |
| 81 | directly associated with a logger, *all handlers associated with all ancestors |
| 82 | of the logger* are called to dispatch the message. |
| 83 | |
| 84 | Just as for loggers, handlers can have levels associated with them. A handler's |
| 85 | level acts as a filter in the same way as a logger's level does. If a handler |
| 86 | decides to actually dispatch an event, the :meth:`emit` method is used to send |
| 87 | the message to its destination. Most user-defined subclasses of :class:`Handler` |
| 88 | will need to override this :meth:`emit`. |
| 89 | |
| 90 | In addition to the base :class:`Handler` class, many useful subclasses are |
| 91 | provided: |
| 92 | |
| 93 | #. :class:`StreamHandler` instances send error messages to streams (file-like |
| 94 | objects). |
| 95 | |
| 96 | #. :class:`FileHandler` instances send error messages to disk files. |
| 97 | |
| 98 | #. :class:`BaseRotatingHandler` is the base class for handlers that rotate log |
| 99 | files at a certain point. It is not meant to be instantiated directly. Instead, |
| 100 | use :class:`RotatingFileHandler` or :class:`TimedRotatingFileHandler`. |
| 101 | |
| 102 | #. :class:`RotatingFileHandler` instances send error messages to disk files, |
| 103 | with support for maximum log file sizes and log file rotation. |
| 104 | |
| 105 | #. :class:`TimedRotatingFileHandler` instances send error messages to disk files |
| 106 | rotating the log file at certain timed intervals. |
| 107 | |
| 108 | #. :class:`SocketHandler` instances send error messages to TCP/IP sockets. |
| 109 | |
| 110 | #. :class:`DatagramHandler` instances send error messages to UDP sockets. |
| 111 | |
| 112 | #. :class:`SMTPHandler` instances send error messages to a designated email |
| 113 | address. |
| 114 | |
| 115 | #. :class:`SysLogHandler` instances send error messages to a Unix syslog daemon, |
| 116 | possibly on a remote machine. |
| 117 | |
| 118 | #. :class:`NTEventLogHandler` instances send error messages to a Windows |
| 119 | NT/2000/XP event log. |
| 120 | |
| 121 | #. :class:`MemoryHandler` instances send error messages to a buffer in memory, |
| 122 | which is flushed whenever specific criteria are met. |
| 123 | |
| 124 | #. :class:`HTTPHandler` instances send error messages to an HTTP server using |
| 125 | either ``GET`` or ``POST`` semantics. |
| 126 | |
| 127 | The :class:`StreamHandler` and :class:`FileHandler` classes are defined in the |
| 128 | core logging package. The other handlers are defined in a sub- module, |
| 129 | :mod:`logging.handlers`. (There is also another sub-module, |
| 130 | :mod:`logging.config`, for configuration functionality.) |
| 131 | |
| 132 | Logged messages are formatted for presentation through instances of the |
| 133 | :class:`Formatter` class. They are initialized with a format string suitable for |
| 134 | use with the % operator and a dictionary. |
| 135 | |
| 136 | For formatting multiple messages in a batch, instances of |
| 137 | :class:`BufferingFormatter` can be used. In addition to the format string (which |
| 138 | is applied to each message in the batch), there is provision for header and |
| 139 | trailer format strings. |
| 140 | |
| 141 | When filtering based on logger level and/or handler level is not enough, |
| 142 | instances of :class:`Filter` can be added to both :class:`Logger` and |
| 143 | :class:`Handler` instances (through their :meth:`addFilter` method). Before |
| 144 | deciding to process a message further, both loggers and handlers consult all |
| 145 | their filters for permission. If any filter returns a false value, the message |
| 146 | is not processed further. |
| 147 | |
| 148 | The basic :class:`Filter` functionality allows filtering by specific logger |
| 149 | name. If this feature is used, messages sent to the named logger and its |
| 150 | children are allowed through the filter, and all others dropped. |
| 151 | |
| 152 | In addition to the classes described above, there are a number of module- level |
| 153 | functions. |
| 154 | |
| 155 | |
| 156 | .. function:: getLogger([name]) |
| 157 | |
| 158 | Return a logger with the specified name or, if no name is specified, return a |
| 159 | logger which is the root logger of the hierarchy. If specified, the name is |
| 160 | typically a dot-separated hierarchical name like *"a"*, *"a.b"* or *"a.b.c.d"*. |
| 161 | Choice of these names is entirely up to the developer who is using logging. |
| 162 | |
| 163 | All calls to this function with a given name return the same logger instance. |
| 164 | This means that logger instances never need to be passed between different parts |
| 165 | of an application. |
| 166 | |
| 167 | |
| 168 | .. function:: getLoggerClass() |
| 169 | |
| 170 | Return either the standard :class:`Logger` class, or the last class passed to |
| 171 | :func:`setLoggerClass`. This function may be called from within a new class |
| 172 | definition, to ensure that installing a customised :class:`Logger` class will |
| 173 | not undo customisations already applied by other code. For example:: |
| 174 | |
| 175 | class MyLogger(logging.getLoggerClass()): |
| 176 | # ... override behaviour here |
| 177 | |
| 178 | |
| 179 | .. function:: debug(msg[, *args[, **kwargs]]) |
| 180 | |
| 181 | Logs a message with level :const:`DEBUG` on the root logger. The *msg* is the |
| 182 | message format string, and the *args* are the arguments which are merged into |
| 183 | *msg* using the string formatting operator. (Note that this means that you can |
| 184 | use keywords in the format string, together with a single dictionary argument.) |
| 185 | |
| 186 | There are two keyword arguments in *kwargs* which are inspected: *exc_info* |
| 187 | which, if it does not evaluate as false, causes exception information to be |
| 188 | added to the logging message. If an exception tuple (in the format returned by |
| 189 | :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info` |
| 190 | is called to get the exception information. |
| 191 | |
| 192 | The other optional keyword argument is *extra* which can be used to pass a |
| 193 | dictionary which is used to populate the __dict__ of the LogRecord created for |
| 194 | the logging event with user-defined attributes. These custom attributes can then |
| 195 | be used as you like. For example, they could be incorporated into logged |
| 196 | messages. For example:: |
| 197 | |
| 198 | FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s" |
| 199 | logging.basicConfig(format=FORMAT) |
| 200 | d = {'clientip': '192.168.0.1', 'user': 'fbloggs'} |
| 201 | logging.warning("Protocol problem: %s", "connection reset", extra=d) |
| 202 | |
| 203 | would print something like :: |
| 204 | |
| 205 | 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset |
| 206 | |
| 207 | The keys in the dictionary passed in *extra* should not clash with the keys used |
| 208 | by the logging system. (See the :class:`Formatter` documentation for more |
| 209 | information on which keys are used by the logging system.) |
| 210 | |
| 211 | If you choose to use these attributes in logged messages, you need to exercise |
| 212 | some care. In the above example, for instance, the :class:`Formatter` has been |
| 213 | set up with a format string which expects 'clientip' and 'user' in the attribute |
| 214 | dictionary of the LogRecord. If these are missing, the message will not be |
| 215 | logged because a string formatting exception will occur. So in this case, you |
| 216 | always need to pass the *extra* dictionary with these keys. |
| 217 | |
| 218 | While this might be annoying, this feature is intended for use in specialized |
| 219 | circumstances, such as multi-threaded servers where the same code executes in |
| 220 | many contexts, and interesting conditions which arise are dependent on this |
| 221 | context (such as remote client IP address and authenticated user name, in the |
| 222 | above example). In such circumstances, it is likely that specialized |
| 223 | :class:`Formatter`\ s would be used with particular :class:`Handler`\ s. |
| 224 | |
| 225 | .. versionchanged:: 2.5 |
| 226 | *extra* was added. |
| 227 | |
| 228 | |
| 229 | .. function:: info(msg[, *args[, **kwargs]]) |
| 230 | |
| 231 | Logs a message with level :const:`INFO` on the root logger. The arguments are |
| 232 | interpreted as for :func:`debug`. |
| 233 | |
| 234 | |
| 235 | .. function:: warning(msg[, *args[, **kwargs]]) |
| 236 | |
| 237 | Logs a message with level :const:`WARNING` on the root logger. The arguments are |
| 238 | interpreted as for :func:`debug`. |
| 239 | |
| 240 | |
| 241 | .. function:: error(msg[, *args[, **kwargs]]) |
| 242 | |
| 243 | Logs a message with level :const:`ERROR` on the root logger. The arguments are |
| 244 | interpreted as for :func:`debug`. |
| 245 | |
| 246 | |
| 247 | .. function:: critical(msg[, *args[, **kwargs]]) |
| 248 | |
| 249 | Logs a message with level :const:`CRITICAL` on the root logger. The arguments |
| 250 | are interpreted as for :func:`debug`. |
| 251 | |
| 252 | |
| 253 | .. function:: exception(msg[, *args]) |
| 254 | |
| 255 | Logs a message with level :const:`ERROR` on the root logger. The arguments are |
| 256 | interpreted as for :func:`debug`. Exception info is added to the logging |
| 257 | message. This function should only be called from an exception handler. |
| 258 | |
| 259 | |
| 260 | .. function:: log(level, msg[, *args[, **kwargs]]) |
| 261 | |
| 262 | Logs a message with level *level* on the root logger. The other arguments are |
| 263 | interpreted as for :func:`debug`. |
| 264 | |
| 265 | |
| 266 | .. function:: disable(lvl) |
| 267 | |
| 268 | Provides an overriding level *lvl* for all loggers which takes precedence over |
| 269 | the logger's own level. When the need arises to temporarily throttle logging |
| 270 | output down across the whole application, this function can be useful. |
| 271 | |
| 272 | |
| 273 | .. function:: addLevelName(lvl, levelName) |
| 274 | |
| 275 | Associates level *lvl* with text *levelName* in an internal dictionary, which is |
| 276 | used to map numeric levels to a textual representation, for example when a |
| 277 | :class:`Formatter` formats a message. This function can also be used to define |
| 278 | your own levels. The only constraints are that all levels used must be |
| 279 | registered using this function, levels should be positive integers and they |
| 280 | should increase in increasing order of severity. |
| 281 | |
| 282 | |
| 283 | .. function:: getLevelName(lvl) |
| 284 | |
| 285 | Returns the textual representation of logging level *lvl*. If the level is one |
| 286 | of the predefined levels :const:`CRITICAL`, :const:`ERROR`, :const:`WARNING`, |
| 287 | :const:`INFO` or :const:`DEBUG` then you get the corresponding string. If you |
| 288 | have associated levels with names using :func:`addLevelName` then the name you |
| 289 | have associated with *lvl* is returned. If a numeric value corresponding to one |
| 290 | of the defined levels is passed in, the corresponding string representation is |
| 291 | returned. Otherwise, the string "Level %s" % lvl is returned. |
| 292 | |
| 293 | |
| 294 | .. function:: makeLogRecord(attrdict) |
| 295 | |
| 296 | Creates and returns a new :class:`LogRecord` instance whose attributes are |
| 297 | defined by *attrdict*. This function is useful for taking a pickled |
| 298 | :class:`LogRecord` attribute dictionary, sent over a socket, and reconstituting |
| 299 | it as a :class:`LogRecord` instance at the receiving end. |
| 300 | |
| 301 | |
| 302 | .. function:: basicConfig([**kwargs]) |
| 303 | |
| 304 | Does basic configuration for the logging system by creating a |
| 305 | :class:`StreamHandler` with a default :class:`Formatter` and adding it to the |
| 306 | root logger. The functions :func:`debug`, :func:`info`, :func:`warning`, |
| 307 | :func:`error` and :func:`critical` will call :func:`basicConfig` automatically |
| 308 | if no handlers are defined for the root logger. |
| 309 | |
| 310 | .. versionchanged:: 2.4 |
| 311 | Formerly, :func:`basicConfig` did not take any keyword arguments. |
| 312 | |
| 313 | The following keyword arguments are supported. |
| 314 | |
| 315 | +--------------+---------------------------------------------+ |
| 316 | | Format | Description | |
| 317 | +==============+=============================================+ |
| 318 | | ``filename`` | Specifies that a FileHandler be created, | |
| 319 | | | using the specified filename, rather than a | |
| 320 | | | StreamHandler. | |
| 321 | +--------------+---------------------------------------------+ |
| 322 | | ``filemode`` | Specifies the mode to open the file, if | |
| 323 | | | filename is specified (if filemode is | |
| 324 | | | unspecified, it defaults to 'a'). | |
| 325 | +--------------+---------------------------------------------+ |
| 326 | | ``format`` | Use the specified format string for the | |
| 327 | | | handler. | |
| 328 | +--------------+---------------------------------------------+ |
| 329 | | ``datefmt`` | Use the specified date/time format. | |
| 330 | +--------------+---------------------------------------------+ |
| 331 | | ``level`` | Set the root logger level to the specified | |
| 332 | | | level. | |
| 333 | +--------------+---------------------------------------------+ |
| 334 | | ``stream`` | Use the specified stream to initialize the | |
| 335 | | | StreamHandler. Note that this argument is | |
| 336 | | | incompatible with 'filename' - if both are | |
| 337 | | | present, 'stream' is ignored. | |
| 338 | +--------------+---------------------------------------------+ |
| 339 | |
| 340 | |
| 341 | .. function:: shutdown() |
| 342 | |
| 343 | Informs the logging system to perform an orderly shutdown by flushing and |
| 344 | closing all handlers. |
| 345 | |
| 346 | |
| 347 | .. function:: setLoggerClass(klass) |
| 348 | |
| 349 | Tells the logging system to use the class *klass* when instantiating a logger. |
| 350 | The class should define :meth:`__init__` such that only a name argument is |
| 351 | required, and the :meth:`__init__` should call :meth:`Logger.__init__`. This |
| 352 | function is typically called before any loggers are instantiated by applications |
| 353 | which need to use custom logger behavior. |
| 354 | |
| 355 | |
| 356 | .. seealso:: |
| 357 | |
| 358 | :pep:`282` - A Logging System |
| 359 | The proposal which described this feature for inclusion in the Python standard |
| 360 | library. |
| 361 | |
| 362 | `Original Python :mod:`logging` package <http://www.red-dove.com/python_logging.html>`_ |
| 363 | This is the original source for the :mod:`logging` package. The version of the |
| 364 | package available from this site is suitable for use with Python 1.5.2, 2.1.x |
| 365 | and 2.2.x, which do not include the :mod:`logging` package in the standard |
| 366 | library. |
| 367 | |
| 368 | |
| 369 | Logger Objects |
| 370 | -------------- |
| 371 | |
| 372 | Loggers have the following attributes and methods. Note that Loggers are never |
| 373 | instantiated directly, but always through the module-level function |
| 374 | ``logging.getLogger(name)``. |
| 375 | |
| 376 | |
| 377 | .. attribute:: Logger.propagate |
| 378 | |
| 379 | If this evaluates to false, logging messages are not passed by this logger or by |
| 380 | child loggers to higher level (ancestor) loggers. The constructor sets this |
| 381 | attribute to 1. |
| 382 | |
| 383 | |
| 384 | .. method:: Logger.setLevel(lvl) |
| 385 | |
| 386 | Sets the threshold for this logger to *lvl*. Logging messages which are less |
| 387 | severe than *lvl* will be ignored. When a logger is created, the level is set to |
| 388 | :const:`NOTSET` (which causes all messages to be processed when the logger is |
| 389 | the root logger, or delegation to the parent when the logger is a non-root |
| 390 | logger). Note that the root logger is created with level :const:`WARNING`. |
| 391 | |
| 392 | The term "delegation to the parent" means that if a logger has a level of |
| 393 | NOTSET, its chain of ancestor loggers is traversed until either an ancestor with |
| 394 | a level other than NOTSET is found, or the root is reached. |
| 395 | |
| 396 | If an ancestor is found with a level other than NOTSET, then that ancestor's |
| 397 | level is treated as the effective level of the logger where the ancestor search |
| 398 | began, and is used to determine how a logging event is handled. |
| 399 | |
| 400 | If the root is reached, and it has a level of NOTSET, then all messages will be |
| 401 | processed. Otherwise, the root's level will be used as the effective level. |
| 402 | |
| 403 | |
| 404 | .. method:: Logger.isEnabledFor(lvl) |
| 405 | |
| 406 | Indicates if a message of severity *lvl* would be processed by this logger. |
| 407 | This method checks first the module-level level set by |
| 408 | ``logging.disable(lvl)`` and then the logger's effective level as determined |
| 409 | by :meth:`getEffectiveLevel`. |
| 410 | |
| 411 | |
| 412 | .. method:: Logger.getEffectiveLevel() |
| 413 | |
| 414 | Indicates the effective level for this logger. If a value other than |
| 415 | :const:`NOTSET` has been set using :meth:`setLevel`, it is returned. Otherwise, |
| 416 | the hierarchy is traversed towards the root until a value other than |
| 417 | :const:`NOTSET` is found, and that value is returned. |
| 418 | |
| 419 | |
| 420 | .. method:: Logger.debug(msg[, *args[, **kwargs]]) |
| 421 | |
| 422 | Logs a message with level :const:`DEBUG` on this logger. The *msg* is the |
| 423 | message format string, and the *args* are the arguments which are merged into |
| 424 | *msg* using the string formatting operator. (Note that this means that you can |
| 425 | use keywords in the format string, together with a single dictionary argument.) |
| 426 | |
| 427 | There are two keyword arguments in *kwargs* which are inspected: *exc_info* |
| 428 | which, if it does not evaluate as false, causes exception information to be |
| 429 | added to the logging message. If an exception tuple (in the format returned by |
| 430 | :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info` |
| 431 | is called to get the exception information. |
| 432 | |
| 433 | The other optional keyword argument is *extra* which can be used to pass a |
| 434 | dictionary which is used to populate the __dict__ of the LogRecord created for |
| 435 | the logging event with user-defined attributes. These custom attributes can then |
| 436 | be used as you like. For example, they could be incorporated into logged |
| 437 | messages. For example:: |
| 438 | |
| 439 | FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s" |
| 440 | logging.basicConfig(format=FORMAT) |
| 441 | dict = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' } |
| 442 | logger = logging.getLogger("tcpserver") |
| 443 | logger.warning("Protocol problem: %s", "connection reset", extra=d) |
| 444 | |
| 445 | would print something like :: |
| 446 | |
| 447 | 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset |
| 448 | |
| 449 | The keys in the dictionary passed in *extra* should not clash with the keys used |
| 450 | by the logging system. (See the :class:`Formatter` documentation for more |
| 451 | information on which keys are used by the logging system.) |
| 452 | |
| 453 | If you choose to use these attributes in logged messages, you need to exercise |
| 454 | some care. In the above example, for instance, the :class:`Formatter` has been |
| 455 | set up with a format string which expects 'clientip' and 'user' in the attribute |
| 456 | dictionary of the LogRecord. If these are missing, the message will not be |
| 457 | logged because a string formatting exception will occur. So in this case, you |
| 458 | always need to pass the *extra* dictionary with these keys. |
| 459 | |
| 460 | While this might be annoying, this feature is intended for use in specialized |
| 461 | circumstances, such as multi-threaded servers where the same code executes in |
| 462 | many contexts, and interesting conditions which arise are dependent on this |
| 463 | context (such as remote client IP address and authenticated user name, in the |
| 464 | above example). In such circumstances, it is likely that specialized |
| 465 | :class:`Formatter`\ s would be used with particular :class:`Handler`\ s. |
| 466 | |
| 467 | .. versionchanged:: 2.5 |
| 468 | *extra* was added. |
| 469 | |
| 470 | |
| 471 | .. method:: Logger.info(msg[, *args[, **kwargs]]) |
| 472 | |
| 473 | Logs a message with level :const:`INFO` on this logger. The arguments are |
| 474 | interpreted as for :meth:`debug`. |
| 475 | |
| 476 | |
| 477 | .. method:: Logger.warning(msg[, *args[, **kwargs]]) |
| 478 | |
| 479 | Logs a message with level :const:`WARNING` on this logger. The arguments are |
| 480 | interpreted as for :meth:`debug`. |
| 481 | |
| 482 | |
| 483 | .. method:: Logger.error(msg[, *args[, **kwargs]]) |
| 484 | |
| 485 | Logs a message with level :const:`ERROR` on this logger. The arguments are |
| 486 | interpreted as for :meth:`debug`. |
| 487 | |
| 488 | |
| 489 | .. method:: Logger.critical(msg[, *args[, **kwargs]]) |
| 490 | |
| 491 | Logs a message with level :const:`CRITICAL` on this logger. The arguments are |
| 492 | interpreted as for :meth:`debug`. |
| 493 | |
| 494 | |
| 495 | .. method:: Logger.log(lvl, msg[, *args[, **kwargs]]) |
| 496 | |
| 497 | Logs a message with integer level *lvl* on this logger. The other arguments are |
| 498 | interpreted as for :meth:`debug`. |
| 499 | |
| 500 | |
| 501 | .. method:: Logger.exception(msg[, *args]) |
| 502 | |
| 503 | Logs a message with level :const:`ERROR` on this logger. The arguments are |
| 504 | interpreted as for :meth:`debug`. Exception info is added to the logging |
| 505 | message. This method should only be called from an exception handler. |
| 506 | |
| 507 | |
| 508 | .. method:: Logger.addFilter(filt) |
| 509 | |
| 510 | Adds the specified filter *filt* to this logger. |
| 511 | |
| 512 | |
| 513 | .. method:: Logger.removeFilter(filt) |
| 514 | |
| 515 | Removes the specified filter *filt* from this logger. |
| 516 | |
| 517 | |
| 518 | .. method:: Logger.filter(record) |
| 519 | |
| 520 | Applies this logger's filters to the record and returns a true value if the |
| 521 | record is to be processed. |
| 522 | |
| 523 | |
| 524 | .. method:: Logger.addHandler(hdlr) |
| 525 | |
| 526 | Adds the specified handler *hdlr* to this logger. |
| 527 | |
| 528 | |
| 529 | .. method:: Logger.removeHandler(hdlr) |
| 530 | |
| 531 | Removes the specified handler *hdlr* from this logger. |
| 532 | |
| 533 | |
| 534 | .. method:: Logger.findCaller() |
| 535 | |
| 536 | Finds the caller's source filename and line number. Returns the filename, line |
| 537 | number and function name as a 3-element tuple. |
| 538 | |
Matthias Klose | f0e2918 | 2007-08-16 12:03:44 +0000 | [diff] [blame] | 539 | .. versionchanged:: 2.4 |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 540 | The function name was added. In earlier versions, the filename and line number |
| 541 | were returned as a 2-element tuple.. |
| 542 | |
| 543 | |
| 544 | .. method:: Logger.handle(record) |
| 545 | |
| 546 | Handles a record by passing it to all handlers associated with this logger and |
| 547 | its ancestors (until a false value of *propagate* is found). This method is used |
| 548 | for unpickled records received from a socket, as well as those created locally. |
| 549 | Logger-level filtering is applied using :meth:`filter`. |
| 550 | |
| 551 | |
| 552 | .. method:: Logger.makeRecord(name, lvl, fn, lno, msg, args, exc_info [, func, extra]) |
| 553 | |
| 554 | This is a factory method which can be overridden in subclasses to create |
| 555 | specialized :class:`LogRecord` instances. |
| 556 | |
| 557 | .. versionchanged:: 2.5 |
| 558 | *func* and *extra* were added. |
| 559 | |
| 560 | |
| 561 | .. _minimal-example: |
| 562 | |
| 563 | Basic example |
| 564 | ------------- |
| 565 | |
| 566 | .. versionchanged:: 2.4 |
| 567 | formerly :func:`basicConfig` did not take any keyword arguments. |
| 568 | |
| 569 | The :mod:`logging` package provides a lot of flexibility, and its configuration |
| 570 | can appear daunting. This section demonstrates that simple use of the logging |
| 571 | package is possible. |
| 572 | |
| 573 | The simplest example shows logging to the console:: |
| 574 | |
| 575 | import logging |
| 576 | |
| 577 | logging.debug('A debug message') |
| 578 | logging.info('Some information') |
| 579 | logging.warning('A shot across the bows') |
| 580 | |
| 581 | If you run the above script, you'll see this:: |
| 582 | |
| 583 | WARNING:root:A shot across the bows |
| 584 | |
| 585 | Because no particular logger was specified, the system used the root logger. The |
| 586 | debug and info messages didn't appear because by default, the root logger is |
| 587 | configured to only handle messages with a severity of WARNING or above. The |
| 588 | message format is also a configuration default, as is the output destination of |
| 589 | the messages - ``sys.stderr``. The severity level, the message format and |
| 590 | destination can be easily changed, as shown in the example below:: |
| 591 | |
| 592 | import logging |
| 593 | |
| 594 | logging.basicConfig(level=logging.DEBUG, |
| 595 | format='%(asctime)s %(levelname)s %(message)s', |
| 596 | filename='/tmp/myapp.log', |
| 597 | filemode='w') |
| 598 | logging.debug('A debug message') |
| 599 | logging.info('Some information') |
| 600 | logging.warning('A shot across the bows') |
| 601 | |
| 602 | The :meth:`basicConfig` method is used to change the configuration defaults, |
| 603 | which results in output (written to ``/tmp/myapp.log``) which should look |
| 604 | something like the following:: |
| 605 | |
| 606 | 2004-07-02 13:00:08,743 DEBUG A debug message |
| 607 | 2004-07-02 13:00:08,743 INFO Some information |
| 608 | 2004-07-02 13:00:08,743 WARNING A shot across the bows |
| 609 | |
| 610 | This time, all messages with a severity of DEBUG or above were handled, and the |
| 611 | format of the messages was also changed, and output went to the specified file |
| 612 | rather than the console. |
| 613 | |
| 614 | Formatting uses standard Python string formatting - see section |
| 615 | :ref:`string-formatting`. The format string takes the following common |
| 616 | specifiers. For a complete list of specifiers, consult the :class:`Formatter` |
| 617 | documentation. |
| 618 | |
| 619 | +-------------------+-----------------------------------------------+ |
| 620 | | Format | Description | |
| 621 | +===================+===============================================+ |
| 622 | | ``%(name)s`` | Name of the logger (logging channel). | |
| 623 | +-------------------+-----------------------------------------------+ |
| 624 | | ``%(levelname)s`` | Text logging level for the message | |
| 625 | | | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, | |
| 626 | | | ``'ERROR'``, ``'CRITICAL'``). | |
| 627 | +-------------------+-----------------------------------------------+ |
| 628 | | ``%(asctime)s`` | Human-readable time when the | |
| 629 | | | :class:`LogRecord` was created. By default | |
| 630 | | | this is of the form "2003-07-08 16:49:45,896" | |
| 631 | | | (the numbers after the comma are millisecond | |
| 632 | | | portion of the time). | |
| 633 | +-------------------+-----------------------------------------------+ |
| 634 | | ``%(message)s`` | The logged message. | |
| 635 | +-------------------+-----------------------------------------------+ |
| 636 | |
| 637 | To change the date/time format, you can pass an additional keyword parameter, |
| 638 | *datefmt*, as in the following:: |
| 639 | |
| 640 | import logging |
| 641 | |
| 642 | logging.basicConfig(level=logging.DEBUG, |
| 643 | format='%(asctime)s %(levelname)-8s %(message)s', |
| 644 | datefmt='%a, %d %b %Y %H:%M:%S', |
| 645 | filename='/temp/myapp.log', |
| 646 | filemode='w') |
| 647 | logging.debug('A debug message') |
| 648 | logging.info('Some information') |
| 649 | logging.warning('A shot across the bows') |
| 650 | |
| 651 | which would result in output like :: |
| 652 | |
| 653 | Fri, 02 Jul 2004 13:06:18 DEBUG A debug message |
| 654 | Fri, 02 Jul 2004 13:06:18 INFO Some information |
| 655 | Fri, 02 Jul 2004 13:06:18 WARNING A shot across the bows |
| 656 | |
| 657 | The date format string follows the requirements of :func:`strftime` - see the |
| 658 | documentation for the :mod:`time` module. |
| 659 | |
| 660 | If, instead of sending logging output to the console or a file, you'd rather use |
| 661 | a file-like object which you have created separately, you can pass it to |
| 662 | :func:`basicConfig` using the *stream* keyword argument. Note that if both |
| 663 | *stream* and *filename* keyword arguments are passed, the *stream* argument is |
| 664 | ignored. |
| 665 | |
| 666 | Of course, you can put variable information in your output. To do this, simply |
| 667 | have the message be a format string and pass in additional arguments containing |
| 668 | the variable information, as in the following example:: |
| 669 | |
| 670 | import logging |
| 671 | |
| 672 | logging.basicConfig(level=logging.DEBUG, |
| 673 | format='%(asctime)s %(levelname)-8s %(message)s', |
| 674 | datefmt='%a, %d %b %Y %H:%M:%S', |
| 675 | filename='/temp/myapp.log', |
| 676 | filemode='w') |
| 677 | logging.error('Pack my box with %d dozen %s', 5, 'liquor jugs') |
| 678 | |
| 679 | which would result in :: |
| 680 | |
| 681 | Wed, 21 Jul 2004 15:35:16 ERROR Pack my box with 5 dozen liquor jugs |
| 682 | |
| 683 | |
| 684 | .. _multiple-destinations: |
| 685 | |
| 686 | Logging to multiple destinations |
| 687 | -------------------------------- |
| 688 | |
| 689 | Let's say you want to log to console and file with different message formats and |
| 690 | in differing circumstances. Say you want to log messages with levels of DEBUG |
| 691 | and higher to file, and those messages at level INFO and higher to the console. |
| 692 | Let's also assume that the file should contain timestamps, but the console |
| 693 | messages should not. Here's how you can achieve this:: |
| 694 | |
| 695 | import logging |
| 696 | |
| 697 | # set up logging to file - see previous section for more details |
| 698 | logging.basicConfig(level=logging.DEBUG, |
| 699 | format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', |
| 700 | datefmt='%m-%d %H:%M', |
| 701 | filename='/temp/myapp.log', |
| 702 | filemode='w') |
| 703 | # define a Handler which writes INFO messages or higher to the sys.stderr |
| 704 | console = logging.StreamHandler() |
| 705 | console.setLevel(logging.INFO) |
| 706 | # set a format which is simpler for console use |
| 707 | formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s') |
| 708 | # tell the handler to use this format |
| 709 | console.setFormatter(formatter) |
| 710 | # add the handler to the root logger |
| 711 | logging.getLogger('').addHandler(console) |
| 712 | |
| 713 | # Now, we can log to the root logger, or any other logger. First the root... |
| 714 | logging.info('Jackdaws love my big sphinx of quartz.') |
| 715 | |
| 716 | # Now, define a couple of other loggers which might represent areas in your |
| 717 | # application: |
| 718 | |
| 719 | logger1 = logging.getLogger('myapp.area1') |
| 720 | logger2 = logging.getLogger('myapp.area2') |
| 721 | |
| 722 | logger1.debug('Quick zephyrs blow, vexing daft Jim.') |
| 723 | logger1.info('How quickly daft jumping zebras vex.') |
| 724 | logger2.warning('Jail zesty vixen who grabbed pay from quack.') |
| 725 | logger2.error('The five boxing wizards jump quickly.') |
| 726 | |
| 727 | When you run this, on the console you will see :: |
| 728 | |
| 729 | root : INFO Jackdaws love my big sphinx of quartz. |
| 730 | myapp.area1 : INFO How quickly daft jumping zebras vex. |
| 731 | myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack. |
| 732 | myapp.area2 : ERROR The five boxing wizards jump quickly. |
| 733 | |
| 734 | and in the file you will see something like :: |
| 735 | |
| 736 | 10-22 22:19 root INFO Jackdaws love my big sphinx of quartz. |
| 737 | 10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim. |
| 738 | 10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex. |
| 739 | 10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack. |
| 740 | 10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly. |
| 741 | |
| 742 | As you can see, the DEBUG message only shows up in the file. The other messages |
| 743 | are sent to both destinations. |
| 744 | |
| 745 | This example uses console and file handlers, but you can use any number and |
| 746 | combination of handlers you choose. |
| 747 | |
| 748 | |
| 749 | .. _network-logging: |
| 750 | |
| 751 | Sending and receiving logging events across a network |
| 752 | ----------------------------------------------------- |
| 753 | |
| 754 | Let's say you want to send logging events across a network, and handle them at |
| 755 | the receiving end. A simple way of doing this is attaching a |
| 756 | :class:`SocketHandler` instance to the root logger at the sending end:: |
| 757 | |
| 758 | import logging, logging.handlers |
| 759 | |
| 760 | rootLogger = logging.getLogger('') |
| 761 | rootLogger.setLevel(logging.DEBUG) |
| 762 | socketHandler = logging.handlers.SocketHandler('localhost', |
| 763 | logging.handlers.DEFAULT_TCP_LOGGING_PORT) |
| 764 | # don't bother with a formatter, since a socket handler sends the event as |
| 765 | # an unformatted pickle |
| 766 | rootLogger.addHandler(socketHandler) |
| 767 | |
| 768 | # Now, we can log to the root logger, or any other logger. First the root... |
| 769 | logging.info('Jackdaws love my big sphinx of quartz.') |
| 770 | |
| 771 | # Now, define a couple of other loggers which might represent areas in your |
| 772 | # application: |
| 773 | |
| 774 | logger1 = logging.getLogger('myapp.area1') |
| 775 | logger2 = logging.getLogger('myapp.area2') |
| 776 | |
| 777 | logger1.debug('Quick zephyrs blow, vexing daft Jim.') |
| 778 | logger1.info('How quickly daft jumping zebras vex.') |
| 779 | logger2.warning('Jail zesty vixen who grabbed pay from quack.') |
| 780 | logger2.error('The five boxing wizards jump quickly.') |
| 781 | |
| 782 | At the receiving end, you can set up a receiver using the :mod:`SocketServer` |
| 783 | module. Here is a basic working example:: |
| 784 | |
| 785 | import cPickle |
| 786 | import logging |
| 787 | import logging.handlers |
| 788 | import SocketServer |
| 789 | import struct |
| 790 | |
| 791 | |
| 792 | class LogRecordStreamHandler(SocketServer.StreamRequestHandler): |
| 793 | """Handler for a streaming logging request. |
| 794 | |
| 795 | This basically logs the record using whatever logging policy is |
| 796 | configured locally. |
| 797 | """ |
| 798 | |
| 799 | def handle(self): |
| 800 | """ |
| 801 | Handle multiple requests - each expected to be a 4-byte length, |
| 802 | followed by the LogRecord in pickle format. Logs the record |
| 803 | according to whatever policy is configured locally. |
| 804 | """ |
| 805 | while 1: |
| 806 | chunk = self.connection.recv(4) |
| 807 | if len(chunk) < 4: |
| 808 | break |
| 809 | slen = struct.unpack(">L", chunk)[0] |
| 810 | chunk = self.connection.recv(slen) |
| 811 | while len(chunk) < slen: |
| 812 | chunk = chunk + self.connection.recv(slen - len(chunk)) |
| 813 | obj = self.unPickle(chunk) |
| 814 | record = logging.makeLogRecord(obj) |
| 815 | self.handleLogRecord(record) |
| 816 | |
| 817 | def unPickle(self, data): |
| 818 | return cPickle.loads(data) |
| 819 | |
| 820 | def handleLogRecord(self, record): |
| 821 | # if a name is specified, we use the named logger rather than the one |
| 822 | # implied by the record. |
| 823 | if self.server.logname is not None: |
| 824 | name = self.server.logname |
| 825 | else: |
| 826 | name = record.name |
| 827 | logger = logging.getLogger(name) |
| 828 | # N.B. EVERY record gets logged. This is because Logger.handle |
| 829 | # is normally called AFTER logger-level filtering. If you want |
| 830 | # to do filtering, do it at the client end to save wasting |
| 831 | # cycles and network bandwidth! |
| 832 | logger.handle(record) |
| 833 | |
| 834 | class LogRecordSocketReceiver(SocketServer.ThreadingTCPServer): |
| 835 | """simple TCP socket-based logging receiver suitable for testing. |
| 836 | """ |
| 837 | |
| 838 | allow_reuse_address = 1 |
| 839 | |
| 840 | def __init__(self, host='localhost', |
| 841 | port=logging.handlers.DEFAULT_TCP_LOGGING_PORT, |
| 842 | handler=LogRecordStreamHandler): |
| 843 | SocketServer.ThreadingTCPServer.__init__(self, (host, port), handler) |
| 844 | self.abort = 0 |
| 845 | self.timeout = 1 |
| 846 | self.logname = None |
| 847 | |
| 848 | def serve_until_stopped(self): |
| 849 | import select |
| 850 | abort = 0 |
| 851 | while not abort: |
| 852 | rd, wr, ex = select.select([self.socket.fileno()], |
| 853 | [], [], |
| 854 | self.timeout) |
| 855 | if rd: |
| 856 | self.handle_request() |
| 857 | abort = self.abort |
| 858 | |
| 859 | def main(): |
| 860 | logging.basicConfig( |
| 861 | format="%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s") |
| 862 | tcpserver = LogRecordSocketReceiver() |
| 863 | print "About to start TCP server..." |
| 864 | tcpserver.serve_until_stopped() |
| 865 | |
| 866 | if __name__ == "__main__": |
| 867 | main() |
| 868 | |
| 869 | First run the server, and then the client. On the client side, nothing is |
| 870 | printed on the console; on the server side, you should see something like:: |
| 871 | |
| 872 | About to start TCP server... |
| 873 | 59 root INFO Jackdaws love my big sphinx of quartz. |
| 874 | 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim. |
| 875 | 69 myapp.area1 INFO How quickly daft jumping zebras vex. |
| 876 | 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack. |
| 877 | 69 myapp.area2 ERROR The five boxing wizards jump quickly. |
| 878 | |
| 879 | |
| 880 | Handler Objects |
| 881 | --------------- |
| 882 | |
| 883 | Handlers have the following attributes and methods. Note that :class:`Handler` |
| 884 | is never instantiated directly; this class acts as a base for more useful |
| 885 | subclasses. However, the :meth:`__init__` method in subclasses needs to call |
| 886 | :meth:`Handler.__init__`. |
| 887 | |
| 888 | |
| 889 | .. method:: Handler.__init__(level=NOTSET) |
| 890 | |
| 891 | Initializes the :class:`Handler` instance by setting its level, setting the list |
| 892 | of filters to the empty list and creating a lock (using :meth:`createLock`) for |
| 893 | serializing access to an I/O mechanism. |
| 894 | |
| 895 | |
| 896 | .. method:: Handler.createLock() |
| 897 | |
| 898 | Initializes a thread lock which can be used to serialize access to underlying |
| 899 | I/O functionality which may not be threadsafe. |
| 900 | |
| 901 | |
| 902 | .. method:: Handler.acquire() |
| 903 | |
| 904 | Acquires the thread lock created with :meth:`createLock`. |
| 905 | |
| 906 | |
| 907 | .. method:: Handler.release() |
| 908 | |
| 909 | Releases the thread lock acquired with :meth:`acquire`. |
| 910 | |
| 911 | |
| 912 | .. method:: Handler.setLevel(lvl) |
| 913 | |
| 914 | Sets the threshold for this handler to *lvl*. Logging messages which are less |
| 915 | severe than *lvl* will be ignored. When a handler is created, the level is set |
| 916 | to :const:`NOTSET` (which causes all messages to be processed). |
| 917 | |
| 918 | |
| 919 | .. method:: Handler.setFormatter(form) |
| 920 | |
| 921 | Sets the :class:`Formatter` for this handler to *form*. |
| 922 | |
| 923 | |
| 924 | .. method:: Handler.addFilter(filt) |
| 925 | |
| 926 | Adds the specified filter *filt* to this handler. |
| 927 | |
| 928 | |
| 929 | .. method:: Handler.removeFilter(filt) |
| 930 | |
| 931 | Removes the specified filter *filt* from this handler. |
| 932 | |
| 933 | |
| 934 | .. method:: Handler.filter(record) |
| 935 | |
| 936 | Applies this handler's filters to the record and returns a true value if the |
| 937 | record is to be processed. |
| 938 | |
| 939 | |
| 940 | .. method:: Handler.flush() |
| 941 | |
| 942 | Ensure all logging output has been flushed. This version does nothing and is |
| 943 | intended to be implemented by subclasses. |
| 944 | |
| 945 | |
| 946 | .. method:: Handler.close() |
| 947 | |
| 948 | Tidy up any resources used by the handler. This version does nothing and is |
| 949 | intended to be implemented by subclasses. |
| 950 | |
| 951 | |
| 952 | .. method:: Handler.handle(record) |
| 953 | |
| 954 | Conditionally emits the specified logging record, depending on filters which may |
| 955 | have been added to the handler. Wraps the actual emission of the record with |
| 956 | acquisition/release of the I/O thread lock. |
| 957 | |
| 958 | |
| 959 | .. method:: Handler.handleError(record) |
| 960 | |
| 961 | This method should be called from handlers when an exception is encountered |
| 962 | during an :meth:`emit` call. By default it does nothing, which means that |
| 963 | exceptions get silently ignored. This is what is mostly wanted for a logging |
| 964 | system - most users will not care about errors in the logging system, they are |
| 965 | more interested in application errors. You could, however, replace this with a |
| 966 | custom handler if you wish. The specified record is the one which was being |
| 967 | processed when the exception occurred. |
| 968 | |
| 969 | |
| 970 | .. method:: Handler.format(record) |
| 971 | |
| 972 | Do formatting for a record - if a formatter is set, use it. Otherwise, use the |
| 973 | default formatter for the module. |
| 974 | |
| 975 | |
| 976 | .. method:: Handler.emit(record) |
| 977 | |
| 978 | Do whatever it takes to actually log the specified logging record. This version |
| 979 | is intended to be implemented by subclasses and so raises a |
| 980 | :exc:`NotImplementedError`. |
| 981 | |
| 982 | |
| 983 | StreamHandler |
| 984 | ^^^^^^^^^^^^^ |
| 985 | |
| 986 | The :class:`StreamHandler` class, located in the core :mod:`logging` package, |
| 987 | sends logging output to streams such as *sys.stdout*, *sys.stderr* or any |
| 988 | file-like object (or, more precisely, any object which supports :meth:`write` |
| 989 | and :meth:`flush` methods). |
| 990 | |
| 991 | |
| 992 | .. class:: StreamHandler([strm]) |
| 993 | |
| 994 | Returns a new instance of the :class:`StreamHandler` class. If *strm* is |
| 995 | specified, the instance will use it for logging output; otherwise, *sys.stderr* |
| 996 | will be used. |
| 997 | |
| 998 | |
| 999 | .. method:: StreamHandler.emit(record) |
| 1000 | |
| 1001 | If a formatter is specified, it is used to format the record. The record is then |
| 1002 | written to the stream with a trailing newline. If exception information is |
| 1003 | present, it is formatted using :func:`traceback.print_exception` and appended to |
| 1004 | the stream. |
| 1005 | |
| 1006 | |
| 1007 | .. method:: StreamHandler.flush() |
| 1008 | |
| 1009 | Flushes the stream by calling its :meth:`flush` method. Note that the |
| 1010 | :meth:`close` method is inherited from :class:`Handler` and so does nothing, so |
| 1011 | an explicit :meth:`flush` call may be needed at times. |
| 1012 | |
| 1013 | |
| 1014 | FileHandler |
| 1015 | ^^^^^^^^^^^ |
| 1016 | |
| 1017 | The :class:`FileHandler` class, located in the core :mod:`logging` package, |
| 1018 | sends logging output to a disk file. It inherits the output functionality from |
| 1019 | :class:`StreamHandler`. |
| 1020 | |
| 1021 | |
| 1022 | .. class:: FileHandler(filename[, mode[, encoding]]) |
| 1023 | |
| 1024 | Returns a new instance of the :class:`FileHandler` class. The specified file is |
| 1025 | opened and used as the stream for logging. If *mode* is not specified, |
| 1026 | :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file |
| 1027 | with that encoding. By default, the file grows indefinitely. |
| 1028 | |
| 1029 | |
| 1030 | .. method:: FileHandler.close() |
| 1031 | |
| 1032 | Closes the file. |
| 1033 | |
| 1034 | |
| 1035 | .. method:: FileHandler.emit(record) |
| 1036 | |
| 1037 | Outputs the record to the file. |
| 1038 | |
| 1039 | |
| 1040 | WatchedFileHandler |
| 1041 | ^^^^^^^^^^^^^^^^^^ |
| 1042 | |
| 1043 | .. versionadded:: 2.6 |
| 1044 | |
| 1045 | The :class:`WatchedFileHandler` class, located in the :mod:`logging.handlers` |
| 1046 | module, is a :class:`FileHandler` which watches the file it is logging to. If |
| 1047 | the file changes, it is closed and reopened using the file name. |
| 1048 | |
| 1049 | A file change can happen because of usage of programs such as *newsyslog* and |
| 1050 | *logrotate* which perform log file rotation. This handler, intended for use |
| 1051 | under Unix/Linux, watches the file to see if it has changed since the last emit. |
| 1052 | (A file is deemed to have changed if its device or inode have changed.) If the |
| 1053 | file has changed, the old file stream is closed, and the file opened to get a |
| 1054 | new stream. |
| 1055 | |
| 1056 | This handler is not appropriate for use under Windows, because under Windows |
| 1057 | open log files cannot be moved or renamed - logging opens the files with |
| 1058 | exclusive locks - and so there is no need for such a handler. Furthermore, |
| 1059 | *ST_INO* is not supported under Windows; :func:`stat` always returns zero for |
| 1060 | this value. |
| 1061 | |
| 1062 | |
| 1063 | .. class:: WatchedFileHandler(filename[,mode[, encoding]]) |
| 1064 | |
| 1065 | Returns a new instance of the :class:`WatchedFileHandler` class. The specified |
| 1066 | file is opened and used as the stream for logging. If *mode* is not specified, |
| 1067 | :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file |
| 1068 | with that encoding. By default, the file grows indefinitely. |
| 1069 | |
| 1070 | |
| 1071 | .. method:: WatchedFileHandler.emit(record) |
| 1072 | |
| 1073 | Outputs the record to the file, but first checks to see if the file has changed. |
| 1074 | If it has, the existing stream is flushed and closed and the file opened again, |
| 1075 | before outputting the record to the file. |
| 1076 | |
| 1077 | |
| 1078 | RotatingFileHandler |
| 1079 | ^^^^^^^^^^^^^^^^^^^ |
| 1080 | |
| 1081 | The :class:`RotatingFileHandler` class, located in the :mod:`logging.handlers` |
| 1082 | module, supports rotation of disk log files. |
| 1083 | |
| 1084 | |
| 1085 | .. class:: RotatingFileHandler(filename[, mode[, maxBytes[, backupCount]]]) |
| 1086 | |
| 1087 | Returns a new instance of the :class:`RotatingFileHandler` class. The specified |
| 1088 | file is opened and used as the stream for logging. If *mode* is not specified, |
| 1089 | ``'a'`` is used. By default, the file grows indefinitely. |
| 1090 | |
| 1091 | You can use the *maxBytes* and *backupCount* values to allow the file to |
| 1092 | :dfn:`rollover` at a predetermined size. When the size is about to be exceeded, |
| 1093 | the file is closed and a new file is silently opened for output. Rollover occurs |
| 1094 | whenever the current log file is nearly *maxBytes* in length; if *maxBytes* is |
| 1095 | zero, rollover never occurs. If *backupCount* is non-zero, the system will save |
| 1096 | old log files by appending the extensions ".1", ".2" etc., to the filename. For |
| 1097 | example, with a *backupCount* of 5 and a base file name of :file:`app.log`, you |
| 1098 | would get :file:`app.log`, :file:`app.log.1`, :file:`app.log.2`, up to |
| 1099 | :file:`app.log.5`. The file being written to is always :file:`app.log`. When |
| 1100 | this file is filled, it is closed and renamed to :file:`app.log.1`, and if files |
| 1101 | :file:`app.log.1`, :file:`app.log.2`, etc. exist, then they are renamed to |
| 1102 | :file:`app.log.2`, :file:`app.log.3` etc. respectively. |
| 1103 | |
| 1104 | |
| 1105 | .. method:: RotatingFileHandler.doRollover() |
| 1106 | |
| 1107 | Does a rollover, as described above. |
| 1108 | |
| 1109 | |
| 1110 | .. method:: RotatingFileHandler.emit(record) |
| 1111 | |
| 1112 | Outputs the record to the file, catering for rollover as described previously. |
| 1113 | |
| 1114 | |
| 1115 | TimedRotatingFileHandler |
| 1116 | ^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1117 | |
| 1118 | The :class:`TimedRotatingFileHandler` class, located in the |
| 1119 | :mod:`logging.handlers` module, supports rotation of disk log files at certain |
| 1120 | timed intervals. |
| 1121 | |
| 1122 | |
| 1123 | .. class:: TimedRotatingFileHandler(filename [,when [,interval [,backupCount]]]) |
| 1124 | |
| 1125 | Returns a new instance of the :class:`TimedRotatingFileHandler` class. The |
| 1126 | specified file is opened and used as the stream for logging. On rotating it also |
| 1127 | sets the filename suffix. Rotating happens based on the product of *when* and |
| 1128 | *interval*. |
| 1129 | |
| 1130 | You can use the *when* to specify the type of *interval*. The list of possible |
| 1131 | values is, note that they are not case sensitive: |
| 1132 | |
| 1133 | +----------+-----------------------+ |
| 1134 | | Value | Type of interval | |
| 1135 | +==========+=======================+ |
| 1136 | | S | Seconds | |
| 1137 | +----------+-----------------------+ |
| 1138 | | M | Minutes | |
| 1139 | +----------+-----------------------+ |
| 1140 | | H | Hours | |
| 1141 | +----------+-----------------------+ |
| 1142 | | D | Days | |
| 1143 | +----------+-----------------------+ |
| 1144 | | W | Week day (0=Monday) | |
| 1145 | +----------+-----------------------+ |
| 1146 | | midnight | Roll over at midnight | |
| 1147 | +----------+-----------------------+ |
| 1148 | |
| 1149 | If *backupCount* is non-zero, the system will save old log files by appending |
| 1150 | extensions to the filename. The extensions are date-and-time based, using the |
| 1151 | strftime format ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on |
| 1152 | the rollover interval. At most *backupCount* files will be kept, and if more |
| 1153 | would be created when rollover occurs, the oldest one is deleted. |
| 1154 | |
| 1155 | |
| 1156 | .. method:: TimedRotatingFileHandler.doRollover() |
| 1157 | |
| 1158 | Does a rollover, as described above. |
| 1159 | |
| 1160 | |
| 1161 | .. method:: TimedRotatingFileHandler.emit(record) |
| 1162 | |
| 1163 | Outputs the record to the file, catering for rollover as described above. |
| 1164 | |
| 1165 | |
| 1166 | SocketHandler |
| 1167 | ^^^^^^^^^^^^^ |
| 1168 | |
| 1169 | The :class:`SocketHandler` class, located in the :mod:`logging.handlers` module, |
| 1170 | sends logging output to a network socket. The base class uses a TCP socket. |
| 1171 | |
| 1172 | |
| 1173 | .. class:: SocketHandler(host, port) |
| 1174 | |
| 1175 | Returns a new instance of the :class:`SocketHandler` class intended to |
| 1176 | communicate with a remote machine whose address is given by *host* and *port*. |
| 1177 | |
| 1178 | |
| 1179 | .. method:: SocketHandler.close() |
| 1180 | |
| 1181 | Closes the socket. |
| 1182 | |
| 1183 | |
| 1184 | .. method:: SocketHandler.emit() |
| 1185 | |
| 1186 | Pickles the record's attribute dictionary and writes it to the socket in binary |
| 1187 | format. If there is an error with the socket, silently drops the packet. If the |
| 1188 | connection was previously lost, re-establishes the connection. To unpickle the |
| 1189 | record at the receiving end into a :class:`LogRecord`, use the |
| 1190 | :func:`makeLogRecord` function. |
| 1191 | |
| 1192 | |
| 1193 | .. method:: SocketHandler.handleError() |
| 1194 | |
| 1195 | Handles an error which has occurred during :meth:`emit`. The most likely cause |
| 1196 | is a lost connection. Closes the socket so that we can retry on the next event. |
| 1197 | |
| 1198 | |
| 1199 | .. method:: SocketHandler.makeSocket() |
| 1200 | |
| 1201 | This is a factory method which allows subclasses to define the precise type of |
| 1202 | socket they want. The default implementation creates a TCP socket |
| 1203 | (:const:`socket.SOCK_STREAM`). |
| 1204 | |
| 1205 | |
| 1206 | .. method:: SocketHandler.makePickle(record) |
| 1207 | |
| 1208 | Pickles the record's attribute dictionary in binary format with a length prefix, |
| 1209 | and returns it ready for transmission across the socket. |
| 1210 | |
| 1211 | |
| 1212 | .. method:: SocketHandler.send(packet) |
| 1213 | |
| 1214 | Send a pickled string *packet* to the socket. This function allows for partial |
| 1215 | sends which can happen when the network is busy. |
| 1216 | |
| 1217 | |
| 1218 | DatagramHandler |
| 1219 | ^^^^^^^^^^^^^^^ |
| 1220 | |
| 1221 | The :class:`DatagramHandler` class, located in the :mod:`logging.handlers` |
| 1222 | module, inherits from :class:`SocketHandler` to support sending logging messages |
| 1223 | over UDP sockets. |
| 1224 | |
| 1225 | |
| 1226 | .. class:: DatagramHandler(host, port) |
| 1227 | |
| 1228 | Returns a new instance of the :class:`DatagramHandler` class intended to |
| 1229 | communicate with a remote machine whose address is given by *host* and *port*. |
| 1230 | |
| 1231 | |
| 1232 | .. method:: DatagramHandler.emit() |
| 1233 | |
| 1234 | Pickles the record's attribute dictionary and writes it to the socket in binary |
| 1235 | format. If there is an error with the socket, silently drops the packet. To |
| 1236 | unpickle the record at the receiving end into a :class:`LogRecord`, use the |
| 1237 | :func:`makeLogRecord` function. |
| 1238 | |
| 1239 | |
| 1240 | .. method:: DatagramHandler.makeSocket() |
| 1241 | |
| 1242 | The factory method of :class:`SocketHandler` is here overridden to create a UDP |
| 1243 | socket (:const:`socket.SOCK_DGRAM`). |
| 1244 | |
| 1245 | |
| 1246 | .. method:: DatagramHandler.send(s) |
| 1247 | |
| 1248 | Send a pickled string to a socket. |
| 1249 | |
| 1250 | |
| 1251 | SysLogHandler |
| 1252 | ^^^^^^^^^^^^^ |
| 1253 | |
| 1254 | The :class:`SysLogHandler` class, located in the :mod:`logging.handlers` module, |
| 1255 | supports sending logging messages to a remote or local Unix syslog. |
| 1256 | |
| 1257 | |
| 1258 | .. class:: SysLogHandler([address[, facility]]) |
| 1259 | |
| 1260 | Returns a new instance of the :class:`SysLogHandler` class intended to |
| 1261 | communicate with a remote Unix machine whose address is given by *address* in |
| 1262 | the form of a ``(host, port)`` tuple. If *address* is not specified, |
| 1263 | ``('localhost', 514)`` is used. The address is used to open a UDP socket. An |
| 1264 | alternative to providing a ``(host, port)`` tuple is providing an address as a |
| 1265 | string, for example "/dev/log". In this case, a Unix domain socket is used to |
| 1266 | send the message to the syslog. If *facility* is not specified, |
| 1267 | :const:`LOG_USER` is used. |
| 1268 | |
| 1269 | |
| 1270 | .. method:: SysLogHandler.close() |
| 1271 | |
| 1272 | Closes the socket to the remote host. |
| 1273 | |
| 1274 | |
| 1275 | .. method:: SysLogHandler.emit(record) |
| 1276 | |
| 1277 | The record is formatted, and then sent to the syslog server. If exception |
| 1278 | information is present, it is *not* sent to the server. |
| 1279 | |
| 1280 | |
| 1281 | .. method:: SysLogHandler.encodePriority(facility, priority) |
| 1282 | |
| 1283 | Encodes the facility and priority into an integer. You can pass in strings or |
| 1284 | integers - if strings are passed, internal mapping dictionaries are used to |
| 1285 | convert them to integers. |
| 1286 | |
| 1287 | |
| 1288 | NTEventLogHandler |
| 1289 | ^^^^^^^^^^^^^^^^^ |
| 1290 | |
| 1291 | The :class:`NTEventLogHandler` class, located in the :mod:`logging.handlers` |
| 1292 | module, supports sending logging messages to a local Windows NT, Windows 2000 or |
| 1293 | Windows XP event log. Before you can use it, you need Mark Hammond's Win32 |
| 1294 | extensions for Python installed. |
| 1295 | |
| 1296 | |
| 1297 | .. class:: NTEventLogHandler(appname[, dllname[, logtype]]) |
| 1298 | |
| 1299 | Returns a new instance of the :class:`NTEventLogHandler` class. The *appname* is |
| 1300 | used to define the application name as it appears in the event log. An |
| 1301 | appropriate registry entry is created using this name. The *dllname* should give |
| 1302 | the fully qualified pathname of a .dll or .exe which contains message |
| 1303 | definitions to hold in the log (if not specified, ``'win32service.pyd'`` is used |
| 1304 | - this is installed with the Win32 extensions and contains some basic |
| 1305 | placeholder message definitions. Note that use of these placeholders will make |
| 1306 | your event logs big, as the entire message source is held in the log. If you |
| 1307 | want slimmer logs, you have to pass in the name of your own .dll or .exe which |
| 1308 | contains the message definitions you want to use in the event log). The |
| 1309 | *logtype* is one of ``'Application'``, ``'System'`` or ``'Security'``, and |
| 1310 | defaults to ``'Application'``. |
| 1311 | |
| 1312 | |
| 1313 | .. method:: NTEventLogHandler.close() |
| 1314 | |
| 1315 | At this point, you can remove the application name from the registry as a source |
| 1316 | of event log entries. However, if you do this, you will not be able to see the |
| 1317 | events as you intended in the Event Log Viewer - it needs to be able to access |
| 1318 | the registry to get the .dll name. The current version does not do this (in fact |
| 1319 | it doesn't do anything). |
| 1320 | |
| 1321 | |
| 1322 | .. method:: NTEventLogHandler.emit(record) |
| 1323 | |
| 1324 | Determines the message ID, event category and event type, and then logs the |
| 1325 | message in the NT event log. |
| 1326 | |
| 1327 | |
| 1328 | .. method:: NTEventLogHandler.getEventCategory(record) |
| 1329 | |
| 1330 | Returns the event category for the record. Override this if you want to specify |
| 1331 | your own categories. This version returns 0. |
| 1332 | |
| 1333 | |
| 1334 | .. method:: NTEventLogHandler.getEventType(record) |
| 1335 | |
| 1336 | Returns the event type for the record. Override this if you want to specify your |
| 1337 | own types. This version does a mapping using the handler's typemap attribute, |
| 1338 | which is set up in :meth:`__init__` to a dictionary which contains mappings for |
| 1339 | :const:`DEBUG`, :const:`INFO`, :const:`WARNING`, :const:`ERROR` and |
| 1340 | :const:`CRITICAL`. If you are using your own levels, you will either need to |
| 1341 | override this method or place a suitable dictionary in the handler's *typemap* |
| 1342 | attribute. |
| 1343 | |
| 1344 | |
| 1345 | .. method:: NTEventLogHandler.getMessageID(record) |
| 1346 | |
| 1347 | Returns the message ID for the record. If you are using your own messages, you |
| 1348 | could do this by having the *msg* passed to the logger being an ID rather than a |
| 1349 | format string. Then, in here, you could use a dictionary lookup to get the |
| 1350 | message ID. This version returns 1, which is the base message ID in |
| 1351 | :file:`win32service.pyd`. |
| 1352 | |
| 1353 | |
| 1354 | SMTPHandler |
| 1355 | ^^^^^^^^^^^ |
| 1356 | |
| 1357 | The :class:`SMTPHandler` class, located in the :mod:`logging.handlers` module, |
| 1358 | supports sending logging messages to an email address via SMTP. |
| 1359 | |
| 1360 | |
| 1361 | .. class:: SMTPHandler(mailhost, fromaddr, toaddrs, subject[, credentials]) |
| 1362 | |
| 1363 | Returns a new instance of the :class:`SMTPHandler` class. The instance is |
| 1364 | initialized with the from and to addresses and subject line of the email. The |
| 1365 | *toaddrs* should be a list of strings. To specify a non-standard SMTP port, use |
| 1366 | the (host, port) tuple format for the *mailhost* argument. If you use a string, |
| 1367 | the standard SMTP port is used. If your SMTP server requires authentication, you |
| 1368 | can specify a (username, password) tuple for the *credentials* argument. |
| 1369 | |
| 1370 | .. versionchanged:: 2.6 |
| 1371 | *credentials* was added. |
| 1372 | |
| 1373 | |
| 1374 | .. method:: SMTPHandler.emit(record) |
| 1375 | |
| 1376 | Formats the record and sends it to the specified addressees. |
| 1377 | |
| 1378 | |
| 1379 | .. method:: SMTPHandler.getSubject(record) |
| 1380 | |
| 1381 | If you want to specify a subject line which is record-dependent, override this |
| 1382 | method. |
| 1383 | |
| 1384 | |
| 1385 | MemoryHandler |
| 1386 | ^^^^^^^^^^^^^ |
| 1387 | |
| 1388 | The :class:`MemoryHandler` class, located in the :mod:`logging.handlers` module, |
| 1389 | supports buffering of logging records in memory, periodically flushing them to a |
| 1390 | :dfn:`target` handler. Flushing occurs whenever the buffer is full, or when an |
| 1391 | event of a certain severity or greater is seen. |
| 1392 | |
| 1393 | :class:`MemoryHandler` is a subclass of the more general |
| 1394 | :class:`BufferingHandler`, which is an abstract class. This buffers logging |
| 1395 | records in memory. Whenever each record is added to the buffer, a check is made |
| 1396 | by calling :meth:`shouldFlush` to see if the buffer should be flushed. If it |
| 1397 | should, then :meth:`flush` is expected to do the needful. |
| 1398 | |
| 1399 | |
| 1400 | .. class:: BufferingHandler(capacity) |
| 1401 | |
| 1402 | Initializes the handler with a buffer of the specified capacity. |
| 1403 | |
| 1404 | |
| 1405 | .. method:: BufferingHandler.emit(record) |
| 1406 | |
| 1407 | Appends the record to the buffer. If :meth:`shouldFlush` returns true, calls |
| 1408 | :meth:`flush` to process the buffer. |
| 1409 | |
| 1410 | |
| 1411 | .. method:: BufferingHandler.flush() |
| 1412 | |
| 1413 | You can override this to implement custom flushing behavior. This version just |
| 1414 | zaps the buffer to empty. |
| 1415 | |
| 1416 | |
| 1417 | .. method:: BufferingHandler.shouldFlush(record) |
| 1418 | |
| 1419 | Returns true if the buffer is up to capacity. This method can be overridden to |
| 1420 | implement custom flushing strategies. |
| 1421 | |
| 1422 | |
| 1423 | .. class:: MemoryHandler(capacity[, flushLevel [, target]]) |
| 1424 | |
| 1425 | Returns a new instance of the :class:`MemoryHandler` class. The instance is |
| 1426 | initialized with a buffer size of *capacity*. If *flushLevel* is not specified, |
| 1427 | :const:`ERROR` is used. If no *target* is specified, the target will need to be |
| 1428 | set using :meth:`setTarget` before this handler does anything useful. |
| 1429 | |
| 1430 | |
| 1431 | .. method:: MemoryHandler.close() |
| 1432 | |
| 1433 | Calls :meth:`flush`, sets the target to :const:`None` and clears the buffer. |
| 1434 | |
| 1435 | |
| 1436 | .. method:: MemoryHandler.flush() |
| 1437 | |
| 1438 | For a :class:`MemoryHandler`, flushing means just sending the buffered records |
| 1439 | to the target, if there is one. Override if you want different behavior. |
| 1440 | |
| 1441 | |
| 1442 | .. method:: MemoryHandler.setTarget(target) |
| 1443 | |
| 1444 | Sets the target handler for this handler. |
| 1445 | |
| 1446 | |
| 1447 | .. method:: MemoryHandler.shouldFlush(record) |
| 1448 | |
| 1449 | Checks for buffer full or a record at the *flushLevel* or higher. |
| 1450 | |
| 1451 | |
| 1452 | HTTPHandler |
| 1453 | ^^^^^^^^^^^ |
| 1454 | |
| 1455 | The :class:`HTTPHandler` class, located in the :mod:`logging.handlers` module, |
| 1456 | supports sending logging messages to a Web server, using either ``GET`` or |
| 1457 | ``POST`` semantics. |
| 1458 | |
| 1459 | |
| 1460 | .. class:: HTTPHandler(host, url[, method]) |
| 1461 | |
| 1462 | Returns a new instance of the :class:`HTTPHandler` class. The instance is |
| 1463 | initialized with a host address, url and HTTP method. The *host* can be of the |
| 1464 | form ``host:port``, should you need to use a specific port number. If no |
| 1465 | *method* is specified, ``GET`` is used. |
| 1466 | |
| 1467 | |
| 1468 | .. method:: HTTPHandler.emit(record) |
| 1469 | |
| 1470 | Sends the record to the Web server as an URL-encoded dictionary. |
| 1471 | |
| 1472 | |
| 1473 | Formatter Objects |
| 1474 | ----------------- |
| 1475 | |
| 1476 | :class:`Formatter`\ s have the following attributes and methods. They are |
| 1477 | responsible for converting a :class:`LogRecord` to (usually) a string which can |
| 1478 | be interpreted by either a human or an external system. The base |
| 1479 | :class:`Formatter` allows a formatting string to be specified. If none is |
| 1480 | supplied, the default value of ``'%(message)s'`` is used. |
| 1481 | |
| 1482 | A Formatter can be initialized with a format string which makes use of knowledge |
| 1483 | of the :class:`LogRecord` attributes - such as the default value mentioned above |
| 1484 | making use of the fact that the user's message and arguments are pre-formatted |
| 1485 | into a :class:`LogRecord`'s *message* attribute. This format string contains |
| 1486 | standard python %-style mapping keys. See section :ref:`string-formatting` |
| 1487 | for more information on string formatting. |
| 1488 | |
| 1489 | Currently, the useful mapping keys in a :class:`LogRecord` are: |
| 1490 | |
| 1491 | +-------------------------+-----------------------------------------------+ |
| 1492 | | Format | Description | |
| 1493 | +=========================+===============================================+ |
| 1494 | | ``%(name)s`` | Name of the logger (logging channel). | |
| 1495 | +-------------------------+-----------------------------------------------+ |
| 1496 | | ``%(levelno)s`` | Numeric logging level for the message | |
| 1497 | | | (:const:`DEBUG`, :const:`INFO`, | |
| 1498 | | | :const:`WARNING`, :const:`ERROR`, | |
| 1499 | | | :const:`CRITICAL`). | |
| 1500 | +-------------------------+-----------------------------------------------+ |
| 1501 | | ``%(levelname)s`` | Text logging level for the message | |
| 1502 | | | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, | |
| 1503 | | | ``'ERROR'``, ``'CRITICAL'``). | |
| 1504 | +-------------------------+-----------------------------------------------+ |
| 1505 | | ``%(pathname)s`` | Full pathname of the source file where the | |
| 1506 | | | logging call was issued (if available). | |
| 1507 | +-------------------------+-----------------------------------------------+ |
| 1508 | | ``%(filename)s`` | Filename portion of pathname. | |
| 1509 | +-------------------------+-----------------------------------------------+ |
| 1510 | | ``%(module)s`` | Module (name portion of filename). | |
| 1511 | +-------------------------+-----------------------------------------------+ |
| 1512 | | ``%(funcName)s`` | Name of function containing the logging call. | |
| 1513 | +-------------------------+-----------------------------------------------+ |
| 1514 | | ``%(lineno)d`` | Source line number where the logging call was | |
| 1515 | | | issued (if available). | |
| 1516 | +-------------------------+-----------------------------------------------+ |
| 1517 | | ``%(created)f`` | Time when the :class:`LogRecord` was created | |
| 1518 | | | (as returned by :func:`time.time`). | |
| 1519 | +-------------------------+-----------------------------------------------+ |
| 1520 | | ``%(relativeCreated)d`` | Time in milliseconds when the LogRecord was | |
| 1521 | | | created, relative to the time the logging | |
| 1522 | | | module was loaded. | |
| 1523 | +-------------------------+-----------------------------------------------+ |
| 1524 | | ``%(asctime)s`` | Human-readable time when the | |
| 1525 | | | :class:`LogRecord` was created. By default | |
| 1526 | | | this is of the form "2003-07-08 16:49:45,896" | |
| 1527 | | | (the numbers after the comma are millisecond | |
| 1528 | | | portion of the time). | |
| 1529 | +-------------------------+-----------------------------------------------+ |
| 1530 | | ``%(msecs)d`` | Millisecond portion of the time when the | |
| 1531 | | | :class:`LogRecord` was created. | |
| 1532 | +-------------------------+-----------------------------------------------+ |
| 1533 | | ``%(thread)d`` | Thread ID (if available). | |
| 1534 | +-------------------------+-----------------------------------------------+ |
| 1535 | | ``%(threadName)s`` | Thread name (if available). | |
| 1536 | +-------------------------+-----------------------------------------------+ |
| 1537 | | ``%(process)d`` | Process ID (if available). | |
| 1538 | +-------------------------+-----------------------------------------------+ |
| 1539 | | ``%(message)s`` | The logged message, computed as ``msg % | |
| 1540 | | | args``. | |
| 1541 | +-------------------------+-----------------------------------------------+ |
| 1542 | |
| 1543 | .. versionchanged:: 2.5 |
| 1544 | *funcName* was added. |
| 1545 | |
| 1546 | |
| 1547 | .. class:: Formatter([fmt[, datefmt]]) |
| 1548 | |
| 1549 | Returns a new instance of the :class:`Formatter` class. The instance is |
| 1550 | initialized with a format string for the message as a whole, as well as a format |
| 1551 | string for the date/time portion of a message. If no *fmt* is specified, |
| 1552 | ``'%(message)s'`` is used. If no *datefmt* is specified, the ISO8601 date format |
| 1553 | is used. |
| 1554 | |
| 1555 | |
| 1556 | .. method:: Formatter.format(record) |
| 1557 | |
| 1558 | The record's attribute dictionary is used as the operand to a string formatting |
| 1559 | operation. Returns the resulting string. Before formatting the dictionary, a |
| 1560 | couple of preparatory steps are carried out. The *message* attribute of the |
| 1561 | record is computed using *msg* % *args*. If the formatting string contains |
| 1562 | ``'(asctime)'``, :meth:`formatTime` is called to format the event time. If there |
| 1563 | is exception information, it is formatted using :meth:`formatException` and |
| 1564 | appended to the message. |
| 1565 | |
| 1566 | |
| 1567 | .. method:: Formatter.formatTime(record[, datefmt]) |
| 1568 | |
| 1569 | This method should be called from :meth:`format` by a formatter which wants to |
| 1570 | make use of a formatted time. This method can be overridden in formatters to |
| 1571 | provide for any specific requirement, but the basic behavior is as follows: if |
| 1572 | *datefmt* (a string) is specified, it is used with :func:`time.strftime` to |
| 1573 | format the creation time of the record. Otherwise, the ISO8601 format is used. |
| 1574 | The resulting string is returned. |
| 1575 | |
| 1576 | |
| 1577 | .. method:: Formatter.formatException(exc_info) |
| 1578 | |
| 1579 | Formats the specified exception information (a standard exception tuple as |
| 1580 | returned by :func:`sys.exc_info`) as a string. This default implementation just |
| 1581 | uses :func:`traceback.print_exception`. The resulting string is returned. |
| 1582 | |
| 1583 | |
| 1584 | Filter Objects |
| 1585 | -------------- |
| 1586 | |
| 1587 | :class:`Filter`\ s can be used by :class:`Handler`\ s and :class:`Logger`\ s for |
| 1588 | more sophisticated filtering than is provided by levels. The base filter class |
| 1589 | only allows events which are below a certain point in the logger hierarchy. For |
| 1590 | example, a filter initialized with "A.B" will allow events logged by loggers |
| 1591 | "A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If |
| 1592 | initialized with the empty string, all events are passed. |
| 1593 | |
| 1594 | |
| 1595 | .. class:: Filter([name]) |
| 1596 | |
| 1597 | Returns an instance of the :class:`Filter` class. If *name* is specified, it |
| 1598 | names a logger which, together with its children, will have its events allowed |
| 1599 | through the filter. If no name is specified, allows every event. |
| 1600 | |
| 1601 | |
| 1602 | .. method:: Filter.filter(record) |
| 1603 | |
| 1604 | Is the specified record to be logged? Returns zero for no, nonzero for yes. If |
| 1605 | deemed appropriate, the record may be modified in-place by this method. |
| 1606 | |
| 1607 | |
| 1608 | LogRecord Objects |
| 1609 | ----------------- |
| 1610 | |
| 1611 | :class:`LogRecord` instances are created every time something is logged. They |
| 1612 | contain all the information pertinent to the event being logged. The main |
| 1613 | information passed in is in msg and args, which are combined using msg % args to |
| 1614 | create the message field of the record. The record also includes information |
| 1615 | such as when the record was created, the source line where the logging call was |
| 1616 | made, and any exception information to be logged. |
| 1617 | |
| 1618 | |
| 1619 | .. class:: LogRecord(name, lvl, pathname, lineno, msg, args, exc_info [, func]) |
| 1620 | |
| 1621 | Returns an instance of :class:`LogRecord` initialized with interesting |
| 1622 | information. The *name* is the logger name; *lvl* is the numeric level; |
| 1623 | *pathname* is the absolute pathname of the source file in which the logging |
| 1624 | call was made; *lineno* is the line number in that file where the logging |
| 1625 | call is found; *msg* is the user-supplied message (a format string); *args* |
| 1626 | is the tuple which, together with *msg*, makes up the user message; and |
| 1627 | *exc_info* is the exception tuple obtained by calling :func:`sys.exc_info` |
| 1628 | (or :const:`None`, if no exception information is available). The *func* is |
| 1629 | the name of the function from which the logging call was made. If not |
| 1630 | specified, it defaults to ``None``. |
| 1631 | |
| 1632 | .. versionchanged:: 2.5 |
| 1633 | *func* was added. |
| 1634 | |
| 1635 | |
| 1636 | .. method:: LogRecord.getMessage() |
| 1637 | |
| 1638 | Returns the message for this :class:`LogRecord` instance after merging any |
| 1639 | user-supplied arguments with the message. |
| 1640 | |
| 1641 | |
| 1642 | Thread Safety |
| 1643 | ------------- |
| 1644 | |
| 1645 | The logging module is intended to be thread-safe without any special work |
| 1646 | needing to be done by its clients. It achieves this though using threading |
| 1647 | locks; there is one lock to serialize access to the module's shared data, and |
| 1648 | each handler also creates a lock to serialize access to its underlying I/O. |
| 1649 | |
| 1650 | |
| 1651 | Configuration |
| 1652 | ------------- |
| 1653 | |
| 1654 | |
| 1655 | .. _logging-config-api: |
| 1656 | |
| 1657 | Configuration functions |
| 1658 | ^^^^^^^^^^^^^^^^^^^^^^^ |
| 1659 | |
| 1660 | .. % |
| 1661 | |
| 1662 | The following functions configure the logging module. They are located in the |
| 1663 | :mod:`logging.config` module. Their use is optional --- you can configure the |
| 1664 | logging module using these functions or by making calls to the main API (defined |
| 1665 | in :mod:`logging` itself) and defining handlers which are declared either in |
| 1666 | :mod:`logging` or :mod:`logging.handlers`. |
| 1667 | |
| 1668 | |
| 1669 | .. function:: fileConfig(fname[, defaults]) |
| 1670 | |
| 1671 | Reads the logging configuration from a ConfigParser-format file named *fname*. |
| 1672 | This function can be called several times from an application, allowing an end |
| 1673 | user the ability to select from various pre-canned configurations (if the |
| 1674 | developer provides a mechanism to present the choices and load the chosen |
| 1675 | configuration). Defaults to be passed to ConfigParser can be specified in the |
| 1676 | *defaults* argument. |
| 1677 | |
| 1678 | |
| 1679 | .. function:: listen([port]) |
| 1680 | |
| 1681 | Starts up a socket server on the specified port, and listens for new |
| 1682 | configurations. If no port is specified, the module's default |
| 1683 | :const:`DEFAULT_LOGGING_CONFIG_PORT` is used. Logging configurations will be |
| 1684 | sent as a file suitable for processing by :func:`fileConfig`. Returns a |
| 1685 | :class:`Thread` instance on which you can call :meth:`start` to start the |
| 1686 | server, and which you can :meth:`join` when appropriate. To stop the server, |
| 1687 | call :func:`stopListening`. To send a configuration to the socket, read in the |
| 1688 | configuration file and send it to the socket as a string of bytes preceded by a |
| 1689 | four-byte length packed in binary using struct.\ ``pack('>L', n)``. |
| 1690 | |
| 1691 | |
| 1692 | .. function:: stopListening() |
| 1693 | |
| 1694 | Stops the listening server which was created with a call to :func:`listen`. This |
| 1695 | is typically called before calling :meth:`join` on the return value from |
| 1696 | :func:`listen`. |
| 1697 | |
| 1698 | |
| 1699 | .. _logging-config-fileformat: |
| 1700 | |
| 1701 | Configuration file format |
| 1702 | ^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1703 | |
| 1704 | .. % |
| 1705 | |
| 1706 | The configuration file format understood by :func:`fileConfig` is based on |
| 1707 | ConfigParser functionality. The file must contain sections called ``[loggers]``, |
| 1708 | ``[handlers]`` and ``[formatters]`` which identify by name the entities of each |
| 1709 | type which are defined in the file. For each such entity, there is a separate |
| 1710 | section which identified how that entity is configured. Thus, for a logger named |
| 1711 | ``log01`` in the ``[loggers]`` section, the relevant configuration details are |
| 1712 | held in a section ``[logger_log01]``. Similarly, a handler called ``hand01`` in |
| 1713 | the ``[handlers]`` section will have its configuration held in a section called |
| 1714 | ``[handler_hand01]``, while a formatter called ``form01`` in the |
| 1715 | ``[formatters]`` section will have its configuration specified in a section |
| 1716 | called ``[formatter_form01]``. The root logger configuration must be specified |
| 1717 | in a section called ``[logger_root]``. |
| 1718 | |
| 1719 | Examples of these sections in the file are given below. :: |
| 1720 | |
| 1721 | [loggers] |
| 1722 | keys=root,log02,log03,log04,log05,log06,log07 |
| 1723 | |
| 1724 | [handlers] |
| 1725 | keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09 |
| 1726 | |
| 1727 | [formatters] |
| 1728 | keys=form01,form02,form03,form04,form05,form06,form07,form08,form09 |
| 1729 | |
| 1730 | The root logger must specify a level and a list of handlers. An example of a |
| 1731 | root logger section is given below. :: |
| 1732 | |
| 1733 | [logger_root] |
| 1734 | level=NOTSET |
| 1735 | handlers=hand01 |
| 1736 | |
| 1737 | The ``level`` entry can be one of ``DEBUG, INFO, WARNING, ERROR, CRITICAL`` or |
| 1738 | ``NOTSET``. For the root logger only, ``NOTSET`` means that all messages will be |
| 1739 | logged. Level values are :func:`eval`\ uated in the context of the ``logging`` |
| 1740 | package's namespace. |
| 1741 | |
| 1742 | The ``handlers`` entry is a comma-separated list of handler names, which must |
| 1743 | appear in the ``[handlers]`` section. These names must appear in the |
| 1744 | ``[handlers]`` section and have corresponding sections in the configuration |
| 1745 | file. |
| 1746 | |
| 1747 | For loggers other than the root logger, some additional information is required. |
| 1748 | This is illustrated by the following example. :: |
| 1749 | |
| 1750 | [logger_parser] |
| 1751 | level=DEBUG |
| 1752 | handlers=hand01 |
| 1753 | propagate=1 |
| 1754 | qualname=compiler.parser |
| 1755 | |
| 1756 | The ``level`` and ``handlers`` entries are interpreted as for the root logger, |
| 1757 | except that if a non-root logger's level is specified as ``NOTSET``, the system |
| 1758 | consults loggers higher up the hierarchy to determine the effective level of the |
| 1759 | logger. The ``propagate`` entry is set to 1 to indicate that messages must |
| 1760 | propagate to handlers higher up the logger hierarchy from this logger, or 0 to |
| 1761 | indicate that messages are **not** propagated to handlers up the hierarchy. The |
| 1762 | ``qualname`` entry is the hierarchical channel name of the logger, that is to |
| 1763 | say the name used by the application to get the logger. |
| 1764 | |
| 1765 | Sections which specify handler configuration are exemplified by the following. |
| 1766 | :: |
| 1767 | |
| 1768 | [handler_hand01] |
| 1769 | class=StreamHandler |
| 1770 | level=NOTSET |
| 1771 | formatter=form01 |
| 1772 | args=(sys.stdout,) |
| 1773 | |
| 1774 | The ``class`` entry indicates the handler's class (as determined by :func:`eval` |
| 1775 | in the ``logging`` package's namespace). The ``level`` is interpreted as for |
| 1776 | loggers, and ``NOTSET`` is taken to mean "log everything". |
| 1777 | |
| 1778 | The ``formatter`` entry indicates the key name of the formatter for this |
| 1779 | handler. If blank, a default formatter (``logging._defaultFormatter``) is used. |
| 1780 | If a name is specified, it must appear in the ``[formatters]`` section and have |
| 1781 | a corresponding section in the configuration file. |
| 1782 | |
| 1783 | The ``args`` entry, when :func:`eval`\ uated in the context of the ``logging`` |
| 1784 | package's namespace, is the list of arguments to the constructor for the handler |
| 1785 | class. Refer to the constructors for the relevant handlers, or to the examples |
| 1786 | below, to see how typical entries are constructed. :: |
| 1787 | |
| 1788 | [handler_hand02] |
| 1789 | class=FileHandler |
| 1790 | level=DEBUG |
| 1791 | formatter=form02 |
| 1792 | args=('python.log', 'w') |
| 1793 | |
| 1794 | [handler_hand03] |
| 1795 | class=handlers.SocketHandler |
| 1796 | level=INFO |
| 1797 | formatter=form03 |
| 1798 | args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT) |
| 1799 | |
| 1800 | [handler_hand04] |
| 1801 | class=handlers.DatagramHandler |
| 1802 | level=WARN |
| 1803 | formatter=form04 |
| 1804 | args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT) |
| 1805 | |
| 1806 | [handler_hand05] |
| 1807 | class=handlers.SysLogHandler |
| 1808 | level=ERROR |
| 1809 | formatter=form05 |
| 1810 | args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER) |
| 1811 | |
| 1812 | [handler_hand06] |
| 1813 | class=handlers.NTEventLogHandler |
| 1814 | level=CRITICAL |
| 1815 | formatter=form06 |
| 1816 | args=('Python Application', '', 'Application') |
| 1817 | |
| 1818 | [handler_hand07] |
| 1819 | class=handlers.SMTPHandler |
| 1820 | level=WARN |
| 1821 | formatter=form07 |
| 1822 | args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject') |
| 1823 | |
| 1824 | [handler_hand08] |
| 1825 | class=handlers.MemoryHandler |
| 1826 | level=NOTSET |
| 1827 | formatter=form08 |
| 1828 | target= |
| 1829 | args=(10, ERROR) |
| 1830 | |
| 1831 | [handler_hand09] |
| 1832 | class=handlers.HTTPHandler |
| 1833 | level=NOTSET |
| 1834 | formatter=form09 |
| 1835 | args=('localhost:9022', '/log', 'GET') |
| 1836 | |
| 1837 | Sections which specify formatter configuration are typified by the following. :: |
| 1838 | |
| 1839 | [formatter_form01] |
| 1840 | format=F1 %(asctime)s %(levelname)s %(message)s |
| 1841 | datefmt= |
| 1842 | class=logging.Formatter |
| 1843 | |
| 1844 | The ``format`` entry is the overall format string, and the ``datefmt`` entry is |
| 1845 | the :func:`strftime`\ -compatible date/time format string. If empty, the package |
| 1846 | substitutes ISO8601 format date/times, which is almost equivalent to specifying |
| 1847 | the date format string "The ISO8601 format also specifies milliseconds, which |
| 1848 | are appended to the result of using the above format string, with a comma |
| 1849 | separator. An example time in ISO8601 format is ``2003-01-23 00:29:50,411``. |
| 1850 | |
| 1851 | .. % Y-%m-%d %H:%M:%S". |
| 1852 | |
| 1853 | The ``class`` entry is optional. It indicates the name of the formatter's class |
| 1854 | (as a dotted module and class name.) This option is useful for instantiating a |
| 1855 | :class:`Formatter` subclass. Subclasses of :class:`Formatter` can present |
| 1856 | exception tracebacks in an expanded or condensed format. |
| 1857 | |