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