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