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