Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 1 | ============= |
| 2 | Logging HOWTO |
| 3 | ============= |
| 4 | |
| 5 | :Author: Vinay Sajip <vinay_sajip at red-dove dot com> |
| 6 | |
| 7 | .. _logging-basic-tutorial: |
| 8 | |
| 9 | .. currentmodule:: logging |
| 10 | |
| 11 | Basic Logging Tutorial |
| 12 | ---------------------- |
| 13 | |
| 14 | Logging is a means of tracking events that happen when some software runs. The |
| 15 | software's developer adds logging calls to their code to indicate that certain |
| 16 | events have occurred. An event is described by a descriptive message which can |
| 17 | optionally contain variable data (i.e. data that is potentially different for |
| 18 | each occurrence of the event). Events also have an importance which the |
| 19 | developer ascribes to the event; the importance can also be called the *level* |
| 20 | or *severity*. |
| 21 | |
| 22 | When to use logging |
| 23 | ^^^^^^^^^^^^^^^^^^^ |
| 24 | |
| 25 | Logging provides a set of convenience functions for simple logging usage. These |
| 26 | are :func:`debug`, :func:`info`, :func:`warning`, :func:`error` and |
| 27 | :func:`critical`. To determine when to use logging, see the table below, which |
| 28 | states, for each of a set of common tasks, the best tool to use for it. |
| 29 | |
| 30 | +-------------------------------------+--------------------------------------+ |
| 31 | | Task you want to perform | The best tool for the task | |
| 32 | +=====================================+======================================+ |
| 33 | | Display console output for ordinary | :func:`print` | |
| 34 | | usage of a command line script or | | |
| 35 | | program | | |
| 36 | +-------------------------------------+--------------------------------------+ |
| 37 | | Report events that occur during | :func:`logging.info` (or | |
| 38 | | normal operation of a program (e.g. | :func:`logging.debug` for very | |
| 39 | | for status monitoring or fault | detailed output for diagnostic | |
| 40 | | investigation) | purposes) | |
| 41 | +-------------------------------------+--------------------------------------+ |
| 42 | | Issue a warning regarding a | :func:`warnings.warn` in library | |
| 43 | | particular runtime event | code if the issue is avoidable and | |
| 44 | | | the client application should be | |
| 45 | | | modified to eliminate the warning | |
| 46 | | | | |
| 47 | | | :func:`logging.warning` if there is | |
| 48 | | | nothing the client application can do| |
| 49 | | | about the situation, but the event | |
| 50 | | | should still be noted | |
| 51 | +-------------------------------------+--------------------------------------+ |
| 52 | | Report an error regarding a | Raise an exception | |
| 53 | | particular runtime event | | |
| 54 | +-------------------------------------+--------------------------------------+ |
| 55 | | Report suppression of an error | :func:`logging.error`, | |
| 56 | | without raising an exception (e.g. | :func:`logging.exception` or | |
| 57 | | error handler in a long-running | :func:`logging.critical` as | |
| 58 | | server process) | appropriate for the specific error | |
| 59 | | | and application domain | |
| 60 | +-------------------------------------+--------------------------------------+ |
| 61 | |
| 62 | The logging functions are named after the level or severity of the events |
| 63 | they are used to track. The standard levels and their applicability are |
| 64 | described below (in increasing order of severity): |
| 65 | |
Georg Brandl | 44ea77b | 2013-03-28 13:28:44 +0100 | [diff] [blame] | 66 | .. tabularcolumns:: |l|L| |
| 67 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 68 | +--------------+---------------------------------------------+ |
| 69 | | Level | When it's used | |
| 70 | +==============+=============================================+ |
| 71 | | ``DEBUG`` | Detailed information, typically of interest | |
| 72 | | | only when diagnosing problems. | |
| 73 | +--------------+---------------------------------------------+ |
| 74 | | ``INFO`` | Confirmation that things are working as | |
| 75 | | | expected. | |
| 76 | +--------------+---------------------------------------------+ |
| 77 | | ``WARNING`` | An indication that something unexpected | |
| 78 | | | happened, or indicative of some problem in | |
| 79 | | | the near future (e.g. 'disk space low'). | |
| 80 | | | The software is still working as expected. | |
| 81 | +--------------+---------------------------------------------+ |
| 82 | | ``ERROR`` | Due to a more serious problem, the software | |
| 83 | | | has not been able to perform some function. | |
| 84 | +--------------+---------------------------------------------+ |
| 85 | | ``CRITICAL`` | A serious error, indicating that the program| |
| 86 | | | itself may be unable to continue running. | |
| 87 | +--------------+---------------------------------------------+ |
| 88 | |
| 89 | The default level is ``WARNING``, which means that only events of this level |
| 90 | and above will be tracked, unless the logging package is configured to do |
| 91 | otherwise. |
| 92 | |
| 93 | Events that are tracked can be handled in different ways. The simplest way of |
| 94 | handling tracked events is to print them to the console. Another common way |
| 95 | is to write them to a disk file. |
| 96 | |
| 97 | |
| 98 | .. _howto-minimal-example: |
| 99 | |
| 100 | A simple example |
| 101 | ^^^^^^^^^^^^^^^^ |
| 102 | |
| 103 | A very simple example is:: |
| 104 | |
| 105 | import logging |
| 106 | logging.warning('Watch out!') # will print a message to the console |
| 107 | logging.info('I told you so') # will not print anything |
| 108 | |
| 109 | If you type these lines into a script and run it, you'll see:: |
| 110 | |
| 111 | WARNING:root:Watch out! |
| 112 | |
| 113 | printed out on the console. The ``INFO`` message doesn't appear because the |
| 114 | default level is ``WARNING``. The printed message includes the indication of |
| 115 | the level and the description of the event provided in the logging call, i.e. |
| 116 | 'Watch out!'. Don't worry about the 'root' part for now: it will be explained |
| 117 | later. The actual output can be formatted quite flexibly if you need that; |
| 118 | formatting options will also be explained later. |
| 119 | |
| 120 | |
| 121 | Logging to a file |
| 122 | ^^^^^^^^^^^^^^^^^ |
| 123 | |
| 124 | A very common situation is that of recording logging events in a file, so let's |
Vinay Sajip | d919da9 | 2013-12-06 11:21:15 +0000 | [diff] [blame] | 125 | look at that next. Be sure to try the following in a newly-started Python |
| 126 | interpreter, and don't just continue from the session described above:: |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 127 | |
| 128 | import logging |
| 129 | logging.basicConfig(filename='example.log',level=logging.DEBUG) |
| 130 | logging.debug('This message should go to the log file') |
| 131 | logging.info('So should this') |
| 132 | logging.warning('And this, too') |
| 133 | |
| 134 | And now if we open the file and look at what we have, we should find the log |
| 135 | messages:: |
| 136 | |
| 137 | DEBUG:root:This message should go to the log file |
| 138 | INFO:root:So should this |
| 139 | WARNING:root:And this, too |
| 140 | |
| 141 | This example also shows how you can set the logging level which acts as the |
| 142 | threshold for tracking. In this case, because we set the threshold to |
| 143 | ``DEBUG``, all of the messages were printed. |
| 144 | |
| 145 | If you want to set the logging level from a command-line option such as:: |
| 146 | |
| 147 | --log=INFO |
| 148 | |
| 149 | and you have the value of the parameter passed for ``--log`` in some variable |
| 150 | *loglevel*, you can use:: |
| 151 | |
| 152 | getattr(logging, loglevel.upper()) |
| 153 | |
| 154 | to get the value which you'll pass to :func:`basicConfig` via the *level* |
| 155 | argument. You may want to error check any user input value, perhaps as in the |
| 156 | following example:: |
| 157 | |
| 158 | # assuming loglevel is bound to the string value obtained from the |
| 159 | # command line argument. Convert to upper case to allow the user to |
| 160 | # specify --log=DEBUG or --log=debug |
| 161 | numeric_level = getattr(logging, loglevel.upper(), None) |
| 162 | if not isinstance(numeric_level, int): |
| 163 | raise ValueError('Invalid log level: %s' % loglevel) |
| 164 | logging.basicConfig(level=numeric_level, ...) |
| 165 | |
| 166 | The call to :func:`basicConfig` should come *before* any calls to :func:`debug`, |
| 167 | :func:`info` etc. As it's intended as a one-off simple configuration facility, |
| 168 | only the first call will actually do anything: subsequent calls are effectively |
| 169 | no-ops. |
| 170 | |
| 171 | If you run the above script several times, the messages from successive runs |
| 172 | are appended to the file *example.log*. If you want each run to start afresh, |
| 173 | not remembering the messages from earlier runs, you can specify the *filemode* |
| 174 | argument, by changing the call in the above example to:: |
| 175 | |
| 176 | logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG) |
| 177 | |
| 178 | The output will be the same as before, but the log file is no longer appended |
| 179 | to, so the messages from earlier runs are lost. |
| 180 | |
| 181 | |
| 182 | Logging from multiple modules |
| 183 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 184 | |
| 185 | If your program consists of multiple modules, here's an example of how you |
| 186 | could organize logging in it:: |
| 187 | |
| 188 | # myapp.py |
| 189 | import logging |
| 190 | import mylib |
| 191 | |
| 192 | def main(): |
| 193 | logging.basicConfig(filename='myapp.log', level=logging.INFO) |
| 194 | logging.info('Started') |
| 195 | mylib.do_something() |
| 196 | logging.info('Finished') |
| 197 | |
| 198 | if __name__ == '__main__': |
| 199 | main() |
| 200 | |
| 201 | :: |
| 202 | |
| 203 | # mylib.py |
| 204 | import logging |
| 205 | |
| 206 | def do_something(): |
| 207 | logging.info('Doing something') |
| 208 | |
| 209 | If you run *myapp.py*, you should see this in *myapp.log*:: |
| 210 | |
| 211 | INFO:root:Started |
| 212 | INFO:root:Doing something |
| 213 | INFO:root:Finished |
| 214 | |
| 215 | which is hopefully what you were expecting to see. You can generalize this to |
| 216 | multiple modules, using the pattern in *mylib.py*. Note that for this simple |
| 217 | usage pattern, you won't know, by looking in the log file, *where* in your |
| 218 | application your messages came from, apart from looking at the event |
| 219 | description. If you want to track the location of your messages, you'll need |
| 220 | to refer to the documentation beyond the tutorial level -- see |
| 221 | :ref:`logging-advanced-tutorial`. |
| 222 | |
| 223 | |
| 224 | Logging variable data |
| 225 | ^^^^^^^^^^^^^^^^^^^^^ |
| 226 | |
| 227 | To log variable data, use a format string for the event description message and |
| 228 | append the variable data as arguments. For example:: |
| 229 | |
| 230 | import logging |
| 231 | logging.warning('%s before you %s', 'Look', 'leap!') |
| 232 | |
| 233 | will display:: |
| 234 | |
| 235 | WARNING:root:Look before you leap! |
| 236 | |
| 237 | As you can see, merging of variable data into the event description message |
| 238 | uses the old, %-style of string formatting. This is for backwards |
| 239 | compatibility: the logging package pre-dates newer formatting options such as |
| 240 | :meth:`str.format` and :class:`string.Template`. These newer formatting |
| 241 | options *are* supported, but exploring them is outside the scope of this |
| 242 | tutorial. |
| 243 | |
| 244 | |
| 245 | Changing the format of displayed messages |
| 246 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 247 | |
| 248 | To change the format which is used to display messages, you need to |
| 249 | specify the format you want to use:: |
| 250 | |
| 251 | import logging |
| 252 | logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG) |
| 253 | logging.debug('This message should appear on the console') |
| 254 | logging.info('So should this') |
| 255 | logging.warning('And this, too') |
| 256 | |
| 257 | which would print:: |
| 258 | |
| 259 | DEBUG:This message should appear on the console |
| 260 | INFO:So should this |
| 261 | WARNING:And this, too |
| 262 | |
| 263 | Notice that the 'root' which appeared in earlier examples has disappeared. For |
| 264 | a full set of things that can appear in format strings, you can refer to the |
| 265 | documentation for :ref:`logrecord-attributes`, but for simple usage, you just |
| 266 | need the *levelname* (severity), *message* (event description, including |
| 267 | variable data) and perhaps to display when the event occurred. This is |
| 268 | described in the next section. |
| 269 | |
| 270 | |
| 271 | Displaying the date/time in messages |
| 272 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 273 | |
| 274 | To display the date and time of an event, you would place '%(asctime)s' in |
| 275 | your format string:: |
| 276 | |
| 277 | import logging |
| 278 | logging.basicConfig(format='%(asctime)s %(message)s') |
| 279 | logging.warning('is when this event was logged.') |
| 280 | |
| 281 | which should print something like this:: |
| 282 | |
| 283 | 2010-12-12 11:41:42,612 is when this event was logged. |
| 284 | |
| 285 | The default format for date/time display (shown above) is ISO8601. If you need |
| 286 | more control over the formatting of the date/time, provide a *datefmt* |
| 287 | argument to ``basicConfig``, as in this example:: |
| 288 | |
| 289 | import logging |
| 290 | logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p') |
| 291 | logging.warning('is when this event was logged.') |
| 292 | |
| 293 | which would display something like this:: |
| 294 | |
| 295 | 12/12/2010 11:46:36 AM is when this event was logged. |
| 296 | |
| 297 | The format of the *datefmt* argument is the same as supported by |
| 298 | :func:`time.strftime`. |
| 299 | |
| 300 | |
| 301 | Next Steps |
| 302 | ^^^^^^^^^^ |
| 303 | |
| 304 | That concludes the basic tutorial. It should be enough to get you up and |
| 305 | running with logging. There's a lot more that the logging package offers, but |
| 306 | to get the best out of it, you'll need to invest a little more of your time in |
| 307 | reading the following sections. If you're ready for that, grab some of your |
| 308 | favourite beverage and carry on. |
| 309 | |
| 310 | If your logging needs are simple, then use the above examples to incorporate |
| 311 | logging into your own scripts, and if you run into problems or don't |
| 312 | understand something, please post a question on the comp.lang.python Usenet |
| 313 | group (available at http://groups.google.com/group/comp.lang.python) and you |
| 314 | should receive help before too long. |
| 315 | |
| 316 | Still here? You can carry on reading the next few sections, which provide a |
| 317 | slightly more advanced/in-depth tutorial than the basic one above. After that, |
| 318 | you can take a look at the :ref:`logging-cookbook`. |
| 319 | |
| 320 | .. _logging-advanced-tutorial: |
| 321 | |
| 322 | |
| 323 | Advanced Logging Tutorial |
| 324 | ------------------------- |
| 325 | |
| 326 | The logging library takes a modular approach and offers several categories |
| 327 | of components: loggers, handlers, filters, and formatters. |
| 328 | |
| 329 | * Loggers expose the interface that application code directly uses. |
| 330 | * Handlers send the log records (created by loggers) to the appropriate |
| 331 | destination. |
| 332 | * Filters provide a finer grained facility for determining which log records |
| 333 | to output. |
| 334 | * Formatters specify the layout of log records in the final output. |
| 335 | |
Vinay Sajip | 0f2bd02 | 2013-01-22 13:10:58 +0000 | [diff] [blame] | 336 | Log event information is passed between loggers, handlers, filters and |
| 337 | formatters in a :class:`LogRecord` instance. |
| 338 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 339 | Logging is performed by calling methods on instances of the :class:`Logger` |
| 340 | class (hereafter called :dfn:`loggers`). Each instance has a name, and they are |
| 341 | conceptually arranged in a namespace hierarchy using dots (periods) as |
| 342 | separators. For example, a logger named 'scan' is the parent of loggers |
| 343 | 'scan.text', 'scan.html' and 'scan.pdf'. Logger names can be anything you want, |
| 344 | and indicate the area of an application in which a logged message originates. |
| 345 | |
| 346 | A good convention to use when naming loggers is to use a module-level logger, |
| 347 | in each module which uses logging, named as follows:: |
| 348 | |
| 349 | logger = logging.getLogger(__name__) |
| 350 | |
| 351 | This means that logger names track the package/module hierarchy, and it's |
| 352 | intuitively obvious where events are logged just from the logger name. |
| 353 | |
| 354 | The root of the hierarchy of loggers is called the root logger. That's the |
| 355 | logger used by the functions :func:`debug`, :func:`info`, :func:`warning`, |
| 356 | :func:`error` and :func:`critical`, which just call the same-named method of |
| 357 | the root logger. The functions and the methods have the same signatures. The |
| 358 | root logger's name is printed as 'root' in the logged output. |
| 359 | |
| 360 | It is, of course, possible to log messages to different destinations. Support |
| 361 | is included in the package for writing log messages to files, HTTP GET/POST |
| 362 | locations, email via SMTP, generic sockets, or OS-specific logging mechanisms |
| 363 | such as syslog or the Windows NT event log. Destinations are served by |
| 364 | :dfn:`handler` classes. You can create your own log destination class if you |
| 365 | have special requirements not met by any of the built-in handler classes. |
| 366 | |
| 367 | By default, no destination is set for any logging messages. You can specify |
| 368 | a destination (such as console or file) by using :func:`basicConfig` as in the |
| 369 | tutorial examples. If you call the functions :func:`debug`, :func:`info`, |
| 370 | :func:`warning`, :func:`error` and :func:`critical`, they will check to see |
| 371 | if no destination is set; and if one is not set, they will set a destination |
| 372 | of the console (``sys.stderr``) and a default format for the displayed |
| 373 | message before delegating to the root logger to do the actual message output. |
| 374 | |
| 375 | The default format set by :func:`basicConfig` for messages is:: |
| 376 | |
| 377 | severity:logger name:message |
| 378 | |
| 379 | You can change this by passing a format string to :func:`basicConfig` with the |
| 380 | *format* keyword argument. For all options regarding how a format string is |
| 381 | constructed, see :ref:`formatter-objects`. |
| 382 | |
Vinay Sajip | 0f2bd02 | 2013-01-22 13:10:58 +0000 | [diff] [blame] | 383 | Logging Flow |
| 384 | ^^^^^^^^^^^^ |
| 385 | |
| 386 | The flow of log event information in loggers and handlers is illustrated in the |
| 387 | following diagram. |
| 388 | |
| 389 | .. image:: logging_flow.png |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 390 | |
| 391 | Loggers |
| 392 | ^^^^^^^ |
| 393 | |
| 394 | :class:`Logger` objects have a threefold job. First, they expose several |
| 395 | methods to application code so that applications can log messages at runtime. |
| 396 | Second, logger objects determine which log messages to act upon based upon |
| 397 | severity (the default filtering facility) or filter objects. Third, logger |
| 398 | objects pass along relevant log messages to all interested log handlers. |
| 399 | |
| 400 | The most widely used methods on logger objects fall into two categories: |
| 401 | configuration and message sending. |
| 402 | |
| 403 | These are the most common configuration methods: |
| 404 | |
| 405 | * :meth:`Logger.setLevel` specifies the lowest-severity log message a logger |
| 406 | will handle, where debug is the lowest built-in severity level and critical |
| 407 | is the highest built-in severity. For example, if the severity level is |
| 408 | INFO, the logger will handle only INFO, WARNING, ERROR, and CRITICAL messages |
| 409 | and will ignore DEBUG messages. |
| 410 | |
| 411 | * :meth:`Logger.addHandler` and :meth:`Logger.removeHandler` add and remove |
| 412 | handler objects from the logger object. Handlers are covered in more detail |
| 413 | in :ref:`handler-basic`. |
| 414 | |
| 415 | * :meth:`Logger.addFilter` and :meth:`Logger.removeFilter` add and remove filter |
| 416 | objects from the logger object. Filters are covered in more detail in |
| 417 | :ref:`filter`. |
| 418 | |
| 419 | You don't need to always call these methods on every logger you create. See the |
| 420 | last two paragraphs in this section. |
| 421 | |
| 422 | With the logger object configured, the following methods create log messages: |
| 423 | |
| 424 | * :meth:`Logger.debug`, :meth:`Logger.info`, :meth:`Logger.warning`, |
| 425 | :meth:`Logger.error`, and :meth:`Logger.critical` all create log records with |
| 426 | a message and a level that corresponds to their respective method names. The |
| 427 | message is actually a format string, which may contain the standard string |
| 428 | substitution syntax of :const:`%s`, :const:`%d`, :const:`%f`, and so on. The |
| 429 | rest of their arguments is a list of objects that correspond with the |
| 430 | substitution fields in the message. With regard to :const:`**kwargs`, the |
| 431 | logging methods care only about a keyword of :const:`exc_info` and use it to |
| 432 | determine whether to log exception information. |
| 433 | |
| 434 | * :meth:`Logger.exception` creates a log message similar to |
| 435 | :meth:`Logger.error`. The difference is that :meth:`Logger.exception` dumps a |
| 436 | stack trace along with it. Call this method only from an exception handler. |
| 437 | |
| 438 | * :meth:`Logger.log` takes a log level as an explicit argument. This is a |
| 439 | little more verbose for logging messages than using the log level convenience |
| 440 | methods listed above, but this is how to log at custom log levels. |
| 441 | |
| 442 | :func:`getLogger` returns a reference to a logger instance with the specified |
| 443 | name if it is provided, or ``root`` if not. The names are period-separated |
| 444 | hierarchical structures. Multiple calls to :func:`getLogger` with the same name |
| 445 | will return a reference to the same logger object. Loggers that are further |
| 446 | down in the hierarchical list are children of loggers higher up in the list. |
| 447 | For example, given a logger with a name of ``foo``, loggers with names of |
| 448 | ``foo.bar``, ``foo.bar.baz``, and ``foo.bam`` are all descendants of ``foo``. |
| 449 | |
| 450 | Loggers have a concept of *effective level*. If a level is not explicitly set |
| 451 | on a logger, the level of its parent is used instead as its effective level. |
| 452 | If the parent has no explicit level set, *its* parent is examined, and so on - |
| 453 | all ancestors are searched until an explicitly set level is found. The root |
| 454 | logger always has an explicit level set (``WARNING`` by default). When deciding |
| 455 | whether to process an event, the effective level of the logger is used to |
| 456 | determine whether the event is passed to the logger's handlers. |
| 457 | |
| 458 | Child loggers propagate messages up to the handlers associated with their |
| 459 | ancestor loggers. Because of this, it is unnecessary to define and configure |
| 460 | handlers for all the loggers an application uses. It is sufficient to |
| 461 | configure handlers for a top-level logger and create child loggers as needed. |
| 462 | (You can, however, turn off propagation by setting the *propagate* |
| 463 | attribute of a logger to *False*.) |
| 464 | |
| 465 | |
| 466 | .. _handler-basic: |
| 467 | |
| 468 | Handlers |
| 469 | ^^^^^^^^ |
| 470 | |
| 471 | :class:`~logging.Handler` objects are responsible for dispatching the |
| 472 | appropriate log messages (based on the log messages' severity) to the handler's |
Vinay Sajip | 10b5130 | 2013-08-17 00:38:48 +0100 | [diff] [blame] | 473 | specified destination. :class:`Logger` objects can add zero or more handler |
| 474 | objects to themselves with an :meth:`~Logger.addHandler` method. As an example |
| 475 | scenario, an application may want to send all log messages to a log file, all |
| 476 | log messages of error or higher to stdout, and all messages of critical to an |
| 477 | email address. This scenario requires three individual handlers where each |
| 478 | handler is responsible for sending messages of a specific severity to a specific |
| 479 | location. |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 480 | |
| 481 | The standard library includes quite a few handler types (see |
| 482 | :ref:`useful-handlers`); the tutorials use mainly :class:`StreamHandler` and |
| 483 | :class:`FileHandler` in its examples. |
| 484 | |
| 485 | There are very few methods in a handler for application developers to concern |
| 486 | themselves with. The only handler methods that seem relevant for application |
| 487 | developers who are using the built-in handler objects (that is, not creating |
| 488 | custom handlers) are the following configuration methods: |
| 489 | |
Vinay Sajip | 10b5130 | 2013-08-17 00:38:48 +0100 | [diff] [blame] | 490 | * The :meth:`~Handler.setLevel` method, just as in logger objects, specifies the |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 491 | lowest severity that will be dispatched to the appropriate destination. Why |
| 492 | are there two :func:`setLevel` methods? The level set in the logger |
| 493 | determines which severity of messages it will pass to its handlers. The level |
| 494 | set in each handler determines which messages that handler will send on. |
| 495 | |
Vinay Sajip | 10b5130 | 2013-08-17 00:38:48 +0100 | [diff] [blame] | 496 | * :meth:`~Handler.setFormatter` selects a Formatter object for this handler to |
| 497 | use. |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 498 | |
Vinay Sajip | 10b5130 | 2013-08-17 00:38:48 +0100 | [diff] [blame] | 499 | * :meth:`~Handler.addFilter` and :meth:`~Handler.removeFilter` respectively |
| 500 | configure and deconfigure filter objects on handlers. |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 501 | |
| 502 | Application code should not directly instantiate and use instances of |
| 503 | :class:`Handler`. Instead, the :class:`Handler` class is a base class that |
| 504 | defines the interface that all handlers should have and establishes some |
| 505 | default behavior that child classes can use (or override). |
| 506 | |
| 507 | |
| 508 | Formatters |
| 509 | ^^^^^^^^^^ |
| 510 | |
| 511 | Formatter objects configure the final order, structure, and contents of the log |
| 512 | message. Unlike the base :class:`logging.Handler` class, application code may |
| 513 | instantiate formatter classes, although you could likely subclass the formatter |
| 514 | if your application needs special behavior. The constructor takes two |
| 515 | optional arguments -- a message format string and a date format string. |
| 516 | |
| 517 | .. method:: logging.Formatter.__init__(fmt=None, datefmt=None) |
| 518 | |
| 519 | If there is no message format string, the default is to use the |
| 520 | raw message. If there is no date format string, the default date format is:: |
| 521 | |
| 522 | %Y-%m-%d %H:%M:%S |
| 523 | |
| 524 | with the milliseconds tacked on at the end. |
| 525 | |
| 526 | The message format string uses ``%(<dictionary key>)s`` styled string |
| 527 | substitution; the possible keys are documented in :ref:`logrecord-attributes`. |
| 528 | |
| 529 | The following message format string will log the time in a human-readable |
| 530 | format, the severity of the message, and the contents of the message, in that |
| 531 | order:: |
| 532 | |
| 533 | '%(asctime)s - %(levelname)s - %(message)s' |
| 534 | |
| 535 | Formatters use a user-configurable function to convert the creation time of a |
| 536 | record to a tuple. By default, :func:`time.localtime` is used; to change this |
| 537 | for a particular formatter instance, set the ``converter`` attribute of the |
| 538 | instance to a function with the same signature as :func:`time.localtime` or |
| 539 | :func:`time.gmtime`. To change it for all formatters, for example if you want |
| 540 | all logging times to be shown in GMT, set the ``converter`` attribute in the |
| 541 | Formatter class (to ``time.gmtime`` for GMT display). |
| 542 | |
| 543 | |
| 544 | Configuring Logging |
| 545 | ^^^^^^^^^^^^^^^^^^^ |
| 546 | |
| 547 | .. currentmodule:: logging.config |
| 548 | |
| 549 | Programmers can configure logging in three ways: |
| 550 | |
| 551 | 1. Creating loggers, handlers, and formatters explicitly using Python |
| 552 | code that calls the configuration methods listed above. |
| 553 | 2. Creating a logging config file and reading it using the :func:`fileConfig` |
| 554 | function. |
| 555 | 3. Creating a dictionary of configuration information and passing it |
| 556 | to the :func:`dictConfig` function. |
| 557 | |
| 558 | For the reference documentation on the last two options, see |
| 559 | :ref:`logging-config-api`. The following example configures a very simple |
| 560 | logger, a console handler, and a simple formatter using Python code:: |
| 561 | |
| 562 | import logging |
| 563 | |
| 564 | # create logger |
| 565 | logger = logging.getLogger('simple_example') |
| 566 | logger.setLevel(logging.DEBUG) |
| 567 | |
| 568 | # create console handler and set level to debug |
| 569 | ch = logging.StreamHandler() |
| 570 | ch.setLevel(logging.DEBUG) |
| 571 | |
| 572 | # create formatter |
| 573 | formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') |
| 574 | |
| 575 | # add formatter to ch |
| 576 | ch.setFormatter(formatter) |
| 577 | |
| 578 | # add ch to logger |
| 579 | logger.addHandler(ch) |
| 580 | |
| 581 | # 'application' code |
| 582 | logger.debug('debug message') |
| 583 | logger.info('info message') |
| 584 | logger.warn('warn message') |
| 585 | logger.error('error message') |
| 586 | logger.critical('critical message') |
| 587 | |
| 588 | Running this module from the command line produces the following output:: |
| 589 | |
| 590 | $ python simple_logging_module.py |
| 591 | 2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message |
| 592 | 2005-03-19 15:10:26,620 - simple_example - INFO - info message |
| 593 | 2005-03-19 15:10:26,695 - simple_example - WARNING - warn message |
| 594 | 2005-03-19 15:10:26,697 - simple_example - ERROR - error message |
| 595 | 2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message |
| 596 | |
| 597 | The following Python module creates a logger, handler, and formatter nearly |
| 598 | identical to those in the example listed above, with the only difference being |
| 599 | the names of the objects:: |
| 600 | |
| 601 | import logging |
| 602 | import logging.config |
| 603 | |
| 604 | logging.config.fileConfig('logging.conf') |
| 605 | |
| 606 | # create logger |
| 607 | logger = logging.getLogger('simpleExample') |
| 608 | |
| 609 | # 'application' code |
| 610 | logger.debug('debug message') |
| 611 | logger.info('info message') |
| 612 | logger.warn('warn message') |
| 613 | logger.error('error message') |
| 614 | logger.critical('critical message') |
| 615 | |
| 616 | Here is the logging.conf file:: |
| 617 | |
| 618 | [loggers] |
| 619 | keys=root,simpleExample |
| 620 | |
| 621 | [handlers] |
| 622 | keys=consoleHandler |
| 623 | |
| 624 | [formatters] |
| 625 | keys=simpleFormatter |
| 626 | |
| 627 | [logger_root] |
| 628 | level=DEBUG |
| 629 | handlers=consoleHandler |
| 630 | |
| 631 | [logger_simpleExample] |
| 632 | level=DEBUG |
| 633 | handlers=consoleHandler |
| 634 | qualname=simpleExample |
| 635 | propagate=0 |
| 636 | |
| 637 | [handler_consoleHandler] |
| 638 | class=StreamHandler |
| 639 | level=DEBUG |
| 640 | formatter=simpleFormatter |
| 641 | args=(sys.stdout,) |
| 642 | |
| 643 | [formatter_simpleFormatter] |
| 644 | format=%(asctime)s - %(name)s - %(levelname)s - %(message)s |
| 645 | datefmt= |
| 646 | |
| 647 | The output is nearly identical to that of the non-config-file-based example:: |
| 648 | |
| 649 | $ python simple_logging_config.py |
| 650 | 2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message |
| 651 | 2005-03-19 15:38:55,979 - simpleExample - INFO - info message |
| 652 | 2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message |
| 653 | 2005-03-19 15:38:56,055 - simpleExample - ERROR - error message |
| 654 | 2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message |
| 655 | |
| 656 | You can see that the config file approach has a few advantages over the Python |
| 657 | code approach, mainly separation of configuration and code and the ability of |
| 658 | noncoders to easily modify the logging properties. |
| 659 | |
Vinay Sajip | 2a1c13b | 2012-04-10 19:52:06 +0100 | [diff] [blame] | 660 | .. warning:: The :func:`fileConfig` function takes a default parameter, |
| 661 | ``disable_existing_loggers``, which defaults to ``True`` for reasons of |
| 662 | backward compatibility. This may or may not be what you want, since it |
| 663 | will cause any loggers existing before the :func:`fileConfig` call to |
| 664 | be disabled unless they (or an ancestor) are explicitly named in the |
| 665 | configuration. Please refer to the reference documentation for more |
| 666 | information, and specify ``False`` for this parameter if you wish. |
| 667 | |
| 668 | The dictionary passed to :func:`dictConfig` can also specify a Boolean |
| 669 | value with key ``disable_existing_loggers``, which if not specified |
| 670 | explicitly in the dictionary also defaults to being interpreted as |
| 671 | ``True``. This leads to the logger-disabling behaviour described above, |
| 672 | which may not be what you want - in which case, provide the key |
| 673 | explicitly with a value of ``False``. |
| 674 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 675 | .. currentmodule:: logging |
| 676 | |
| 677 | Note that the class names referenced in config files need to be either relative |
| 678 | to the logging module, or absolute values which can be resolved using normal |
| 679 | import mechanisms. Thus, you could use either |
| 680 | :class:`~logging.handlers.WatchedFileHandler` (relative to the logging module) or |
| 681 | ``mypackage.mymodule.MyHandler`` (for a class defined in package ``mypackage`` |
| 682 | and module ``mymodule``, where ``mypackage`` is available on the Python import |
| 683 | path). |
| 684 | |
| 685 | In Python 2.7, a new means of configuring logging has been introduced, using |
| 686 | dictionaries to hold configuration information. This provides a superset of the |
| 687 | functionality of the config-file-based approach outlined above, and is the |
| 688 | recommended configuration method for new applications and deployments. Because |
| 689 | a Python dictionary is used to hold configuration information, and since you |
| 690 | can populate that dictionary using different means, you have more options for |
| 691 | configuration. For example, you can use a configuration file in JSON format, |
| 692 | or, if you have access to YAML processing functionality, a file in YAML |
| 693 | format, to populate the configuration dictionary. Or, of course, you can |
| 694 | construct the dictionary in Python code, receive it in pickled form over a |
| 695 | socket, or use whatever approach makes sense for your application. |
| 696 | |
| 697 | Here's an example of the same configuration as above, in YAML format for |
| 698 | the new dictionary-based approach:: |
| 699 | |
| 700 | version: 1 |
| 701 | formatters: |
| 702 | simple: |
Vinay Sajip | fa4736e | 2011-09-06 14:06:24 +0100 | [diff] [blame] | 703 | format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s' |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 704 | handlers: |
| 705 | console: |
| 706 | class: logging.StreamHandler |
| 707 | level: DEBUG |
| 708 | formatter: simple |
| 709 | stream: ext://sys.stdout |
| 710 | loggers: |
| 711 | simpleExample: |
| 712 | level: DEBUG |
| 713 | handlers: [console] |
| 714 | propagate: no |
| 715 | root: |
| 716 | level: DEBUG |
| 717 | handlers: [console] |
| 718 | |
| 719 | For more information about logging using a dictionary, see |
| 720 | :ref:`logging-config-api`. |
| 721 | |
| 722 | What happens if no configuration is provided |
| 723 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 724 | |
| 725 | If no logging configuration is provided, it is possible to have a situation |
| 726 | where a logging event needs to be output, but no handlers can be found to |
| 727 | output the event. The behaviour of the logging package in these |
| 728 | circumstances is dependent on the Python version. |
| 729 | |
| 730 | For Python 2.x, the behaviour is as follows: |
| 731 | |
| 732 | * If *logging.raiseExceptions* is *False* (production mode), the event is |
| 733 | silently dropped. |
| 734 | |
| 735 | * If *logging.raiseExceptions* is *True* (development mode), a message |
| 736 | 'No handlers could be found for logger X.Y.Z' is printed once. |
| 737 | |
| 738 | .. _library-config: |
| 739 | |
| 740 | Configuring Logging for a Library |
| 741 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 742 | |
| 743 | When developing a library which uses logging, you should take care to |
| 744 | document how the library uses logging - for example, the names of loggers |
| 745 | used. Some consideration also needs to be given to its logging configuration. |
Vinay Sajip | b322621 | 2013-01-29 22:36:39 +0000 | [diff] [blame] | 746 | If the using application does not configure logging, and library code makes |
| 747 | logging calls, then (as described in the previous section) an error message |
| 748 | will be printed to ``sys.stderr``. |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 749 | |
Vinay Sajip | b322621 | 2013-01-29 22:36:39 +0000 | [diff] [blame] | 750 | If for some reason you *don't* want this message printed in the absence of |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 751 | any logging configuration, you can attach a do-nothing handler to the top-level |
| 752 | logger for your library. This avoids the message being printed, since a handler |
| 753 | will be always be found for the library's events: it just doesn't produce any |
| 754 | output. If the library user configures logging for application use, presumably |
| 755 | that configuration will add some handlers, and if levels are suitably |
| 756 | configured then logging calls made in library code will send output to those |
| 757 | handlers, as normal. |
| 758 | |
| 759 | A do-nothing handler is included in the logging package: |
| 760 | :class:`~logging.NullHandler` (since Python 2.7). An instance of this handler |
| 761 | could be added to the top-level logger of the logging namespace used by the |
Vinay Sajip | b322621 | 2013-01-29 22:36:39 +0000 | [diff] [blame] | 762 | library (*if* you want to prevent an error message being output to |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 763 | ``sys.stderr`` in the absence of logging configuration). If all logging by a |
| 764 | library *foo* is done using loggers with names matching 'foo.x', 'foo.x.y', |
| 765 | etc. then the code:: |
| 766 | |
| 767 | import logging |
| 768 | logging.getLogger('foo').addHandler(logging.NullHandler()) |
| 769 | |
| 770 | should have the desired effect. If an organisation produces a number of |
| 771 | libraries, then the logger name specified can be 'orgname.foo' rather than |
| 772 | just 'foo'. |
| 773 | |
Vinay Sajip | 3a5fc4b | 2013-01-08 11:18:42 +0000 | [diff] [blame] | 774 | .. note:: It is strongly advised that you *do not add any handlers other |
| 775 | than* :class:`~logging.NullHandler` *to your library's loggers*. This is |
| 776 | because the configuration of handlers is the prerogative of the application |
| 777 | developer who uses your library. The application developer knows their |
| 778 | target audience and what handlers are most appropriate for their |
| 779 | application: if you add handlers 'under the hood', you might well interfere |
| 780 | with their ability to carry out unit tests and deliver logs which suit their |
| 781 | requirements. |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 782 | |
| 783 | |
| 784 | Logging Levels |
| 785 | -------------- |
| 786 | |
| 787 | The numeric values of logging levels are given in the following table. These are |
| 788 | primarily of interest if you want to define your own levels, and need them to |
| 789 | have specific values relative to the predefined levels. If you define a level |
| 790 | with the same numeric value, it overwrites the predefined value; the predefined |
| 791 | name is lost. |
| 792 | |
| 793 | +--------------+---------------+ |
| 794 | | Level | Numeric value | |
| 795 | +==============+===============+ |
| 796 | | ``CRITICAL`` | 50 | |
| 797 | +--------------+---------------+ |
| 798 | | ``ERROR`` | 40 | |
| 799 | +--------------+---------------+ |
| 800 | | ``WARNING`` | 30 | |
| 801 | +--------------+---------------+ |
| 802 | | ``INFO`` | 20 | |
| 803 | +--------------+---------------+ |
| 804 | | ``DEBUG`` | 10 | |
| 805 | +--------------+---------------+ |
| 806 | | ``NOTSET`` | 0 | |
| 807 | +--------------+---------------+ |
| 808 | |
| 809 | Levels can also be associated with loggers, being set either by the developer or |
| 810 | through loading a saved logging configuration. When a logging method is called |
| 811 | on a logger, the logger compares its own level with the level associated with |
| 812 | the method call. If the logger's level is higher than the method call's, no |
| 813 | logging message is actually generated. This is the basic mechanism controlling |
| 814 | the verbosity of logging output. |
| 815 | |
| 816 | Logging messages are encoded as instances of the :class:`~logging.LogRecord` |
| 817 | class. When a logger decides to actually log an event, a |
| 818 | :class:`~logging.LogRecord` instance is created from the logging message. |
| 819 | |
| 820 | Logging messages are subjected to a dispatch mechanism through the use of |
| 821 | :dfn:`handlers`, which are instances of subclasses of the :class:`Handler` |
| 822 | class. Handlers are responsible for ensuring that a logged message (in the form |
| 823 | of a :class:`LogRecord`) ends up in a particular location (or set of locations) |
| 824 | which is useful for the target audience for that message (such as end users, |
| 825 | support desk staff, system administrators, developers). Handlers are passed |
| 826 | :class:`LogRecord` instances intended for particular destinations. Each logger |
| 827 | can have zero, one or more handlers associated with it (via the |
| 828 | :meth:`~Logger.addHandler` method of :class:`Logger`). In addition to any |
| 829 | handlers directly associated with a logger, *all handlers associated with all |
| 830 | ancestors of the logger* are called to dispatch the message (unless the |
| 831 | *propagate* flag for a logger is set to a false value, at which point the |
| 832 | passing to ancestor handlers stops). |
| 833 | |
| 834 | Just as for loggers, handlers can have levels associated with them. A handler's |
| 835 | level acts as a filter in the same way as a logger's level does. If a handler |
| 836 | decides to actually dispatch an event, the :meth:`~Handler.emit` method is used |
| 837 | to send the message to its destination. Most user-defined subclasses of |
| 838 | :class:`Handler` will need to override this :meth:`~Handler.emit`. |
| 839 | |
| 840 | .. _custom-levels: |
| 841 | |
| 842 | Custom Levels |
| 843 | ^^^^^^^^^^^^^ |
| 844 | |
| 845 | Defining your own levels is possible, but should not be necessary, as the |
| 846 | existing levels have been chosen on the basis of practical experience. |
| 847 | However, if you are convinced that you need custom levels, great care should |
| 848 | be exercised when doing this, and it is possibly *a very bad idea to define |
| 849 | custom levels if you are developing a library*. That's because if multiple |
| 850 | library authors all define their own custom levels, there is a chance that |
| 851 | the logging output from such multiple libraries used together will be |
| 852 | difficult for the using developer to control and/or interpret, because a |
| 853 | given numeric value might mean different things for different libraries. |
| 854 | |
| 855 | .. _useful-handlers: |
| 856 | |
| 857 | Useful Handlers |
| 858 | --------------- |
| 859 | |
| 860 | In addition to the base :class:`Handler` class, many useful subclasses are |
| 861 | provided: |
| 862 | |
| 863 | #. :class:`StreamHandler` instances send messages to streams (file-like |
| 864 | objects). |
| 865 | |
| 866 | #. :class:`FileHandler` instances send messages to disk files. |
| 867 | |
| 868 | #. :class:`~handlers.BaseRotatingHandler` is the base class for handlers that |
| 869 | rotate log files at a certain point. It is not meant to be instantiated |
| 870 | directly. Instead, use :class:`~handlers.RotatingFileHandler` or |
| 871 | :class:`~handlers.TimedRotatingFileHandler`. |
| 872 | |
| 873 | #. :class:`~handlers.RotatingFileHandler` instances send messages to disk |
| 874 | files, with support for maximum log file sizes and log file rotation. |
| 875 | |
| 876 | #. :class:`~handlers.TimedRotatingFileHandler` instances send messages to |
| 877 | disk files, rotating the log file at certain timed intervals. |
| 878 | |
| 879 | #. :class:`~handlers.SocketHandler` instances send messages to TCP/IP |
| 880 | sockets. |
| 881 | |
| 882 | #. :class:`~handlers.DatagramHandler` instances send messages to UDP |
| 883 | sockets. |
| 884 | |
| 885 | #. :class:`~handlers.SMTPHandler` instances send messages to a designated |
| 886 | email address. |
| 887 | |
| 888 | #. :class:`~handlers.SysLogHandler` instances send messages to a Unix |
| 889 | syslog daemon, possibly on a remote machine. |
| 890 | |
| 891 | #. :class:`~handlers.NTEventLogHandler` instances send messages to a |
| 892 | Windows NT/2000/XP event log. |
| 893 | |
| 894 | #. :class:`~handlers.MemoryHandler` instances send messages to a buffer |
| 895 | in memory, which is flushed whenever specific criteria are met. |
| 896 | |
| 897 | #. :class:`~handlers.HTTPHandler` instances send messages to an HTTP |
| 898 | server using either ``GET`` or ``POST`` semantics. |
| 899 | |
| 900 | #. :class:`~handlers.WatchedFileHandler` instances watch the file they are |
| 901 | logging to. If the file changes, it is closed and reopened using the file |
| 902 | name. This handler is only useful on Unix-like systems; Windows does not |
| 903 | support the underlying mechanism used. |
| 904 | |
| 905 | #. :class:`NullHandler` instances do nothing with error messages. They are used |
| 906 | by library developers who want to use logging, but want to avoid the 'No |
| 907 | handlers could be found for logger XXX' message which can be displayed if |
| 908 | the library user has not configured logging. See :ref:`library-config` for |
| 909 | more information. |
| 910 | |
| 911 | .. versionadded:: 2.7 |
| 912 | The :class:`NullHandler` class. |
| 913 | |
| 914 | The :class:`NullHandler`, :class:`StreamHandler` and :class:`FileHandler` |
| 915 | classes are defined in the core logging package. The other handlers are |
| 916 | defined in a sub- module, :mod:`logging.handlers`. (There is also another |
| 917 | sub-module, :mod:`logging.config`, for configuration functionality.) |
| 918 | |
| 919 | Logged messages are formatted for presentation through instances of the |
| 920 | :class:`Formatter` class. They are initialized with a format string suitable for |
| 921 | use with the % operator and a dictionary. |
| 922 | |
| 923 | For formatting multiple messages in a batch, instances of |
Vinay Sajip | 10b5130 | 2013-08-17 00:38:48 +0100 | [diff] [blame] | 924 | :class:`~handlers.BufferingFormatter` can be used. In addition to the format |
| 925 | string (which is applied to each message in the batch), there is provision for |
| 926 | header and trailer format strings. |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 927 | |
| 928 | When filtering based on logger level and/or handler level is not enough, |
| 929 | instances of :class:`Filter` can be added to both :class:`Logger` and |
Vinay Sajip | 10b5130 | 2013-08-17 00:38:48 +0100 | [diff] [blame] | 930 | :class:`Handler` instances (through their :meth:`~Handler.addFilter` method). |
| 931 | Before deciding to process a message further, both loggers and handlers consult |
| 932 | all their filters for permission. If any filter returns a false value, the |
| 933 | message is not processed further. |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 934 | |
| 935 | The basic :class:`Filter` functionality allows filtering by specific logger |
| 936 | name. If this feature is used, messages sent to the named logger and its |
| 937 | children are allowed through the filter, and all others dropped. |
| 938 | |
| 939 | |
| 940 | .. _logging-exceptions: |
| 941 | |
| 942 | Exceptions raised during logging |
| 943 | -------------------------------- |
| 944 | |
| 945 | The logging package is designed to swallow exceptions which occur while logging |
| 946 | in production. This is so that errors which occur while handling logging events |
| 947 | - such as logging misconfiguration, network or other similar errors - do not |
| 948 | cause the application using logging to terminate prematurely. |
| 949 | |
| 950 | :class:`SystemExit` and :class:`KeyboardInterrupt` exceptions are never |
Vinay Sajip | 10b5130 | 2013-08-17 00:38:48 +0100 | [diff] [blame] | 951 | swallowed. Other exceptions which occur during the :meth:`~Handler.emit` method |
| 952 | of a :class:`Handler` subclass are passed to its :meth:`~Handler.handleError` |
| 953 | method. |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 954 | |
Vinay Sajip | 10b5130 | 2013-08-17 00:38:48 +0100 | [diff] [blame] | 955 | The default implementation of :meth:`~Handler.handleError` in :class:`Handler` |
| 956 | checks to see if a module-level variable, :data:`raiseExceptions`, is set. If |
| 957 | set, a traceback is printed to :data:`sys.stderr`. If not set, the exception is |
| 958 | swallowed. |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 959 | |
Vinay Sajip | 3a5fc4b | 2013-01-08 11:18:42 +0000 | [diff] [blame] | 960 | .. note:: The default value of :data:`raiseExceptions` is ``True``. This is |
| 961 | because during development, you typically want to be notified of any |
| 962 | exceptions that occur. It's advised that you set :data:`raiseExceptions` to |
| 963 | ``False`` for production usage. |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 964 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 965 | |
| 966 | .. _arbitrary-object-messages: |
| 967 | |
| 968 | Using arbitrary objects as messages |
| 969 | ----------------------------------- |
| 970 | |
| 971 | In the preceding sections and examples, it has been assumed that the message |
| 972 | passed when logging the event is a string. However, this is not the only |
| 973 | possibility. You can pass an arbitrary object as a message, and its |
Vinay Sajip | 10b5130 | 2013-08-17 00:38:48 +0100 | [diff] [blame] | 974 | :meth:`~object.__str__` method will be called when the logging system needs to |
| 975 | convert it to a string representation. In fact, if you want to, you can avoid |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 976 | computing a string representation altogether - for example, the |
Vinay Sajip | 10b5130 | 2013-08-17 00:38:48 +0100 | [diff] [blame] | 977 | :class:`~handlers.SocketHandler` emits an event by pickling it and sending it |
| 978 | over the wire. |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 979 | |
| 980 | |
| 981 | Optimization |
| 982 | ------------ |
| 983 | |
| 984 | Formatting of message arguments is deferred until it cannot be avoided. |
| 985 | However, computing the arguments passed to the logging method can also be |
| 986 | expensive, and you may want to avoid doing it if the logger will just throw |
Vinay Sajip | 10b5130 | 2013-08-17 00:38:48 +0100 | [diff] [blame] | 987 | away your event. To decide what to do, you can call the |
| 988 | :meth:`~Logger.isEnabledFor` method which takes a level argument and returns |
| 989 | true if the event would be created by the Logger for that level of call. |
| 990 | You can write code like this:: |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 991 | |
| 992 | if logger.isEnabledFor(logging.DEBUG): |
| 993 | logger.debug('Message with %s, %s', expensive_func1(), |
| 994 | expensive_func2()) |
| 995 | |
| 996 | so that if the logger's threshold is set above ``DEBUG``, the calls to |
| 997 | :func:`expensive_func1` and :func:`expensive_func2` are never made. |
| 998 | |
Vinay Sajip | 7de9971 | 2014-06-25 07:29:19 +0100 | [diff] [blame] | 999 | .. note:: In some cases, :meth:`~Logger.isEnabledFor` can itself be more |
Vinay Sajip | 9e51f50 | 2014-06-02 00:24:47 +0100 | [diff] [blame] | 1000 | expensive than you'd like (e.g. for deeply nested loggers where an explicit |
| 1001 | level is only set high up in the logger hierarchy). In such cases (or if you |
| 1002 | want to avoid calling a method in tight loops), you can cache the result of a |
| 1003 | call to :meth:`~Logger.isEnabledFor` in a local or instance variable, and use |
| 1004 | that instead of calling the method each time. Such a cached value would only |
| 1005 | need to be recomputed when the logging configuration changes dynamically |
| 1006 | while the application is running (which is not all that common). |
| 1007 | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 1008 | There are other optimizations which can be made for specific applications which |
| 1009 | need more precise control over what logging information is collected. Here's a |
| 1010 | list of things you can do to avoid processing during logging which you don't |
| 1011 | need: |
| 1012 | |
| 1013 | +-----------------------------------------------+----------------------------------------+ |
| 1014 | | What you don't want to collect | How to avoid collecting it | |
| 1015 | +===============================================+========================================+ |
| 1016 | | Information about where calls were made from. | Set ``logging._srcfile`` to ``None``. | |
Vinay Sajip | 9e51f50 | 2014-06-02 00:24:47 +0100 | [diff] [blame] | 1017 | | | This avoids calling | |
| 1018 | | | :func:`sys._getframe`, which may help | |
| 1019 | | | to speed up your code in environments | |
| 1020 | | | like PyPy (which can't speed up code | |
| 1021 | | | that uses :func:`sys._getframe`). | |
Vinay Sajip | 5dbca9c | 2011-04-08 11:40:38 +0100 | [diff] [blame] | 1022 | +-----------------------------------------------+----------------------------------------+ |
| 1023 | | Threading information. | Set ``logging.logThreads`` to ``0``. | |
| 1024 | +-----------------------------------------------+----------------------------------------+ |
| 1025 | | Process information. | Set ``logging.logProcesses`` to ``0``. | |
| 1026 | +-----------------------------------------------+----------------------------------------+ |
| 1027 | |
| 1028 | Also note that the core logging module only includes the basic handlers. If |
| 1029 | you don't import :mod:`logging.handlers` and :mod:`logging.config`, they won't |
| 1030 | take up any memory. |
| 1031 | |
| 1032 | .. seealso:: |
| 1033 | |
| 1034 | Module :mod:`logging` |
| 1035 | API reference for the logging module. |
| 1036 | |
| 1037 | Module :mod:`logging.config` |
| 1038 | Configuration API for the logging module. |
| 1039 | |
| 1040 | Module :mod:`logging.handlers` |
| 1041 | Useful handlers included with the logging module. |
| 1042 | |
| 1043 | :ref:`A logging cookbook <logging-cookbook>` |
| 1044 | |