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