blob: 490f69ff04e86ed988ff1347499deef88c819109 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`logging` --- Logging facility for Python
2==============================================
3
4.. module:: logging
Vinay Sajip1d5d6852010-12-12 22:47:13 +00005 :synopsis: Flexible event logging system for applications.
Georg Brandl116aa622007-08-15 14:28:22 +00006
7
8.. moduleauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
9.. sectionauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
10
11
Georg Brandl116aa622007-08-15 14:28:22 +000012.. index:: pair: Errors; logging
13
Vinay Sajip1d5d6852010-12-12 22:47:13 +000014This module defines functions and classes which implement a flexible event
Vinay Sajip36675b62010-12-12 22:30:17 +000015logging system for applications and libraries.
Georg Brandl116aa622007-08-15 14:28:22 +000016
Vinay Sajipa18b9592010-12-12 13:20:55 +000017The key benefit of having the logging API provided by a standard library module
18is that all Python modules can participate in logging, so your application log
19can include your own messages integrated with messages from third-party
20modules.
21
22
23Logging tutorial
24----------------
25
26Logging is a means of tracking events that happen when some software runs. The
27software's developer adds logging calls to their code to indicate that certain
28events have occurred. An event is described by a descriptive message which can
29optionally contain variable data (i.e. data that is potentially different for
30each occurrence of the event). Events also have an importance which the
31developer ascribes to the event; the importance can also be called the *level*
32or *severity*.
33
34When to use logging
35^^^^^^^^^^^^^^^^^^^
36
37Logging provides a set of convenience functions for simple logging usage. These
38are :func:`debug`, :func:`info`, :func:`warning`, :func:`error` and
39:func:`critical`. To determine when to use logging, see the table below, which
40states, for each of a set of common tasks, the best tool to use for it.
41
42+-------------------------------------+--------------------------------------+
43| Task you want to perform | The best tool for the task |
44+=====================================+======================================+
45| Display console output for ordinary | print() |
46| usage of a command line script or | |
47| program | |
48+-------------------------------------+--------------------------------------+
49| Report events that occur during | logging.info() (or logging.debug() |
50| normal operation of a program (e.g. | for very detailed output for |
Vinay Sajipf234eb92010-12-12 17:37:27 +000051| for status monitoring or fault | diagnostic purposes) |
Vinay Sajipa18b9592010-12-12 13:20:55 +000052| investigation) | |
53+-------------------------------------+--------------------------------------+
54| Issue a warning regarding a | warnings.warn() in library code |
55| particular runtime event | if the issue is avoidable and the |
56| | client application should be |
57| | modified to eliminate the warning |
58| | |
59| | logging.warn() if there is nothing |
60| | the client application can do about |
61| | the situation, but the event should |
62| | still be noted |
63+-------------------------------------+--------------------------------------+
64| Report an error regarding a | Raise an exception |
65| particular runtime event | |
66+-------------------------------------+--------------------------------------+
67| Report suppression of an error | logging.error(), logging.exception(),|
68| without raising an exception (e.g. | or logging.critical() as appropriate |
69| error handler in a long-running | for the specific error and |
70| server process) | application domain |
71+-------------------------------------+--------------------------------------+
72
73The logging functions are named after the level or severity of the events
74they are used to track. The standard levels and their applicability are
75described below (in increasing order of severity):
76
77+--------------+---------------------------------------------+
78| Level | When it's used |
79+==============+=============================================+
80| ``DEBUG`` | Detailed information, typically of interest |
81| | only when diagnosing problems. |
82+--------------+---------------------------------------------+
83| ``INFO`` | Confirmation that things are working as |
84| | expected. |
85+--------------+---------------------------------------------+
86| ``WARNING`` | An indication that something unexpected |
87| | happened, or indicative of some problem in |
88| | the near future (e.g. "disk space low"). |
89| | The software is still working as expected. |
90+--------------+---------------------------------------------+
91| ``ERROR`` | Due to a more serious problem, the software |
92| | has not been able to perform some function. |
93+--------------+---------------------------------------------+
94| ``CRITICAL`` | A serious error, indicating that the program|
95| | itself may be unable to continue running. |
96+--------------+---------------------------------------------+
97
98The default level is ``WARNING``, which means that only events of this level
99and above will be tracked, unless the logging package is configured to do
100otherwise.
101
102Events that are tracked can be handled in different ways. The simplest way of
103handling tracked events is to print them to the console. Another common way
104is to write them to a disk file.
105
106
107.. _minimal-example:
108
109A simple example
110^^^^^^^^^^^^^^^^
111
112A very simple example is::
113
114 import logging
115 logging.warning('Watch out!') # will print a message to the console
116 logging.info('I told you so') # will not print anything
117
118If you type these lines into a script and run it, you'll see::
119
120 WARNING:root:Watch out!
121
122printed out on the console. The ``INFO`` message doesn't appear because the
123default level is ``WARNING``. The printed message includes the indication of
124the level and the description of the event provided in the logging call, i.e.
125'Watch out!'. Don't worry about the 'root' part for now: it will be explained
126later. The actual output can be formatted quite flexibly if you need that;
127formatting options will also be explained later.
128
129
130Logging to a file
131^^^^^^^^^^^^^^^^^
132
133A very common situation is that of recording logging events in a file, so let's
134look at that next::
135
136 import logging
137 logging.basicConfig(filename='example.log',level=logging.DEBUG)
138 logging.debug('This message should go to the log file')
139 logging.info('So should this')
140 logging.warning('And this, too')
141
142And now if we open the file and look at what we have, we should find the log
143messages::
144
145 DEBUG:root:This message should go to the log file
146 INFO:root:So should this
147 WARNING:root:And this, too
148
Vinay Sajip97b886d2010-12-12 22:45:35 +0000149This example also shows how you can set the logging level which acts as the
150threshold for tracking. In this case, because we set the threshold to
151``DEBUG``, all of the messages were printed.
152
153If you want to set the logging level from a command-line option such as::
154
155 --log=INFO
156
157and you have the value of the parameter passed for ``--log`` in some variable
158*loglevel*, you can use::
159
160 getattr(logging, loglevel.upper())
161
162to get the value which you'll pass to :func:`basicConfig` via the *level*
163argument. You may want to error check any user input value, perhaps as in the
164following example::
165
166 # assuming loglevel is bound to the string value obtained from the
167 # command line argument. Convert to upper case to allow the user to
168 # specify --log=DEBUG or --log=debug
169 numeric_level = getattr(logging, loglevel.upper(), None)
170 assert numeric_level is not None, 'Invalid log level: %s' % loglevel
171 logging.basicConfig(level=numeric_level, ...)
172
Vinay Sajip0e65cf02010-12-12 13:49:39 +0000173The call to :func:`basicConfig` should come *before* any calls to :func:`debug`,
174:func:`info` etc. As it's intended as a one-off simple configuration facility,
175only the first call will actually do anything: subsequent calls are effectively
176no-ops.
177
Vinay Sajipa18b9592010-12-12 13:20:55 +0000178If you run the above script several times, the messages from successive runs
179are appended to the file *example.log*. If you want each run to start afresh,
180not remembering the messages from earlier runs, you can specify the *filemode*
181argument, by changing the call in the above example to::
182
183 logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG)
184
185The output will be the same as before, but the log file is no longer appended
186to, so the messages from earlier runs are lost.
187
188
189Logging from multiple modules
190^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
191
192If your program consists of multiple modules, here's an example of how you
193could organize logging in it::
194
195 # myapp.py
196 import logging
197 import mylib
198
199 def main():
200 logging.basicConfig(filename='myapp.log', level=logging.INFO)
201 logging.info('Started')
202 mylib.do_something()
203 logging.info('Finished')
204
205 if __name__ == '__main__':
206 main()
207
208::
209
210 # mylib.py
211 import logging
212
213 def do_something():
214 logging.info('Doing something')
215
216If you run myapp.py, you should see this in myapp.log::
217
218 INFO:root:Started
219 INFO:root:Doing something
220 INFO:root:Finished
221
222which is hopefully what you were expecting to see. You can generalize this to
223multiple modules, using the pattern in *mylib.py*. Note that for this simple
224usage pattern, you won't know, by looking in the log file, *where* in your
225application your messages came from, apart from looking at the event
226description. If you want to track the location of your messages, you'll need
227to refer to the documentation beyond the tutorial level - see
228:ref:`more-advanced-logging`.
229
230
231Logging variable data
232^^^^^^^^^^^^^^^^^^^^^
233
234To log variable data, use a format string for the event description message and
235append the variable data as arguments. For example::
236
237 import logging
238 logging.warning('%s before you %s', 'Look', 'leap!')
239
240will display::
241
242 WARNING:root:Look before you leap!
243
244As you can see, merging of variable data into the event description message
245uses the old, %-style of string formatting. This is for backwards
246compatibility: the logging package pre-dates newer formatting options such as
Vinay Sajip36675b62010-12-12 22:30:17 +0000247:meth:`str.format` and :class:`string.Template`. These newer formatting
248options *are* supported, but exploring them is outside the scope of this
249tutorial.
Vinay Sajipa18b9592010-12-12 13:20:55 +0000250
251
252Changing the format of displayed messages
253^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
254
255To change the format which is used to display messages, you need to
256specify the format you want to use::
257
258 import logging
259 logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
260 logging.debug('This message should appear on the console')
261 logging.info('So should this')
262 logging.warning('And this, too')
263
264which would print::
265
266 DEBUG:This message should appear on the console
267 INFO:So should this
268 WARNING:And this, too
269
270Notice that the 'root' which appeared in earlier examples has disappeared. For
271a full set of things that can appear in format strings, you can refer to the
272documentation for :ref:`formatter-objects`, but for simple usage, you just need
273the *levelname* (severity), *message* (event description, including variable
274data) and perhaps to display when the event occurred. This is described in the
275next section.
276
277Displaying the date/time in messages
278^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
279
280To display the date and time of an event, you would place "%(asctime)s" in
281your format string::
282
283 import logging
284 logging.basicConfig(format='%(asctime)s %(message)s')
285 logging.warning('is when this event was logged.')
286
287which should print something like this::
288
289 2010-12-12 11:41:42,612 is when this event was logged.
290
291The default format for date/time display (shown above) is ISO8601. If you need
292more control over the formatting of the date/time, provide a *datefmt*
293argument to ``basicConfig``, as in this example::
294
295 import logging
296 logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
297 logging.warning('is when this event was logged.')
298
299which would display something like this::
300
301 12/12/2010 11:46:36 AM is when this event was logged.
302
303The format of the *datefmt* argument is the same as supported by
304:func:`time.strftime`.
305
306
Vinay Sajipf234eb92010-12-12 17:37:27 +0000307Er...that's it for the basics
308^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Vinay Sajipa18b9592010-12-12 13:20:55 +0000309
Vinay Sajipf234eb92010-12-12 17:37:27 +0000310That concludes the basic tutorial. It should be enough to get you up and
311running with logging. There's a lot more that the logging package offers, but
312to get the best out of it, you'll need to invest a little more of your time in
Vinay Sajipa18b9592010-12-12 13:20:55 +0000313reading the following sections. If you're ready for that, grab some of your
314favourite beverage and carry on.
315
316If your logging needs are simple, then use the above examples to incorporate
317logging into your own scripts, and if you run into problems or don't
318understand something, please post a question on the comp.lang.python Usenet
319group (available at http://groups.google.com/group/comp.lang.python) and you
320should receive help before too long.
321
Vinay Sajipf234eb92010-12-12 17:37:27 +0000322Still here? There's no need to read the whole of the logging documentation in
323linear fashion, top to bottom (there's quite a lot of it still to come). You
324can carry on reading the next few sections, which provide a slightly more
325advanced/in-depth tutorial than the basic one above. After that, you can
326take a look at the topics in the sidebar to see if there's something that
327especially interests you, and click on a topic to see more detail. Although
328some of the topics do follow on from each other, there are a few that can just
329stand alone.
Vinay Sajipa18b9592010-12-12 13:20:55 +0000330
331
332.. _more-advanced-logging:
333
334More advanced logging
335---------------------
336
337The logging library takes a modular approach and offers several categories
338of components: loggers, handlers, filters, and formatters. Loggers expose the
339interface that application code directly uses. Handlers send the log records
340(created by loggers) to the appropriate destination. Filters provide a finer
341grained facility for determining which log records to output. Formatters
342specify the layout of the resultant log record in the final output.
343
Georg Brandl116aa622007-08-15 14:28:22 +0000344Logging is performed by calling methods on instances of the :class:`Logger`
345class (hereafter called :dfn:`loggers`). Each instance has a name, and they are
Georg Brandl9afde1c2007-11-01 20:32:30 +0000346conceptually arranged in a namespace hierarchy using dots (periods) as
Georg Brandl116aa622007-08-15 14:28:22 +0000347separators. For example, a logger named "scan" is the parent of loggers
348"scan.text", "scan.html" and "scan.pdf". Logger names can be anything you want,
349and indicate the area of an application in which a logged message originates.
350
Vinay Sajip5286ccf2010-12-12 13:25:29 +0000351A good convention to use when naming loggers is to use a module-level logger,
352in each module which uses logging, named as follows::
353
354 logger = logging.getLogger(__name__)
355
356This means that logger names track the package/module hierarchy, and it's
357intuitively obvious where events are logged just from the logger name.
358
Vinay Sajipa18b9592010-12-12 13:20:55 +0000359The root of the hierarchy of loggers is called the root logger. That's the
360logger used by the functions :func:`debug`, :func:`info`, :func:`warning`,
361:func:`error` and :func:`critical`, which just call the same-named method of
362the root logger. The functions and the methods have the same signatures. The
363root logger's name is printed as 'root' in the logged output.
Georg Brandl116aa622007-08-15 14:28:22 +0000364
Vinay Sajipa18b9592010-12-12 13:20:55 +0000365It is, of course, possible to log messages to different destinations. Support
366for writing log messages to files, HTTP GET/POST locations, email via SMTP,
367generic sockets, or OS-specific logging mechanisms is included in the package.
368Destinations are served by :dfn:`handler` classes. You can create your own log
Vinay Sajipdfa0a2a2010-12-10 08:17:05 +0000369destination class if you have special requirements not met by any of the
Vinay Sajipa18b9592010-12-12 13:20:55 +0000370built-in handler classes.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000371
Vinay Sajipa18b9592010-12-12 13:20:55 +0000372By default, no destination is set for any logging messages. You can specify
373a destination (such as console or file) by using :func:`basicConfig` as in the
374tutorial examples. If you call the functions :func:`debug`, :func:`info`,
375:func:`warning`, :func:`error` and :func:`critical`, they will check to see
376if no destination is set; and if one is not set, they will set a destination
377of the console (``sys.stderr``) and a default format for the displayed
378message before delegating to the root logger to do the actual message output.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000379
Vinay Sajipa18b9592010-12-12 13:20:55 +0000380The default format set by :func:`basicConfig` for messages is::
Christian Heimes8b0facf2007-12-04 19:30:01 +0000381
Vinay Sajipa18b9592010-12-12 13:20:55 +0000382 severity:logger name:message
Christian Heimes8b0facf2007-12-04 19:30:01 +0000383
Vinay Sajipa18b9592010-12-12 13:20:55 +0000384You can change this by passing a format string to :func:`basicConfig` with the
385*format* keyword argument. For all options regarding how a format string is
386constructed, see :ref:`formatter-objects`.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000387
Christian Heimes8b0facf2007-12-04 19:30:01 +0000388
389Loggers
390^^^^^^^
391
Christian Heimes8b0facf2007-12-04 19:30:01 +0000392:class:`Logger` objects have a threefold job. First, they expose several
393methods to application code so that applications can log messages at runtime.
394Second, logger objects determine which log messages to act upon based upon
395severity (the default filtering facility) or filter objects. Third, logger
396objects pass along relevant log messages to all interested log handlers.
397
398The most widely used methods on logger objects fall into two categories:
399configuration and message sending.
400
Vinay Sajipf234eb92010-12-12 17:37:27 +0000401These are the most common configuration methods:
402
Christian Heimes8b0facf2007-12-04 19:30:01 +0000403* :meth:`Logger.setLevel` specifies the lowest-severity log message a logger
Vinay Sajipf234eb92010-12-12 17:37:27 +0000404 will handle, where debug is the lowest built-in severity level and critical
405 is the highest built-in severity. For example, if the severity level is
406 INFO, the logger will handle only INFO, WARNING, ERROR, and CRITICAL messages
407 and will ignore DEBUG messages.
408
409* :meth:`Logger.addHandler` and :meth:`Logger.removeHandler` add and remove
410 handler objects from the logger object. Handlers are covered in more detail
411 in :ref:`handler-basic`.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000412
413* :meth:`Logger.addFilter` and :meth:`Logger.removeFilter` add and remove filter
Vinay Sajipf234eb92010-12-12 17:37:27 +0000414 objects from the logger object. Filters are covered in more detail in
415 :ref:`filter`.
416
417You don't need to always call these methods on every logger you create. See the
418last two paragraphs in this section.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000419
420With the logger object configured, the following methods create log messages:
421
422* :meth:`Logger.debug`, :meth:`Logger.info`, :meth:`Logger.warning`,
423 :meth:`Logger.error`, and :meth:`Logger.critical` all create log records with
424 a message and a level that corresponds to their respective method names. The
425 message is actually a format string, which may contain the standard string
426 substitution syntax of :const:`%s`, :const:`%d`, :const:`%f`, and so on. The
427 rest of their arguments is a list of objects that correspond with the
428 substitution fields in the message. With regard to :const:`**kwargs`, the
429 logging methods care only about a keyword of :const:`exc_info` and use it to
430 determine whether to log exception information.
431
432* :meth:`Logger.exception` creates a log message similar to
433 :meth:`Logger.error`. The difference is that :meth:`Logger.exception` dumps a
434 stack trace along with it. Call this method only from an exception handler.
435
436* :meth:`Logger.log` takes a log level as an explicit argument. This is a
437 little more verbose for logging messages than using the log level convenience
438 methods listed above, but this is how to log at custom log levels.
439
Christian Heimesdcca98d2008-02-25 13:19:43 +0000440:func:`getLogger` returns a reference to a logger instance with the specified
Vinay Sajipc15dfd62010-07-06 15:08:55 +0000441name if it is provided, or ``root`` if not. The names are period-separated
Christian Heimes8b0facf2007-12-04 19:30:01 +0000442hierarchical structures. Multiple calls to :func:`getLogger` with the same name
443will return a reference to the same logger object. Loggers that are further
444down in the hierarchical list are children of loggers higher up in the list.
445For example, given a logger with a name of ``foo``, loggers with names of
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000446``foo.bar``, ``foo.bar.baz``, and ``foo.bam`` are all descendants of ``foo``.
Vinay Sajipf234eb92010-12-12 17:37:27 +0000447
448Loggers have a concept of *effective level*. If a level is not explicitly set
449on a logger, the level of its parent is used instead as its effective level.
450If the parent has no explicit level set, *its* parent is examined, and so on -
451all ancestors are searched until an explicitly set level is found. The root
452logger always has an explicit level set (``WARNING`` by default). When deciding
453whether to process an event, the effective level of the logger is used to
454determine whether the event is passed to the logger's handlers.
455
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000456Child loggers propagate messages up to the handlers associated with their
Vinay Sajipf234eb92010-12-12 17:37:27 +0000457ancestor loggers. Because of this, it is unnecessary to define and configure
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000458handlers for all the loggers an application uses. It is sufficient to
459configure handlers for a top-level logger and create child loggers as needed.
Vinay Sajipf234eb92010-12-12 17:37:27 +0000460(You can, however, turn off propagation by setting the *propagate*
461attribute of a logger to *False*.)
Christian Heimes8b0facf2007-12-04 19:30:01 +0000462
463
Vinay Sajipf234eb92010-12-12 17:37:27 +0000464.. _handler-basic:
465
Christian Heimes8b0facf2007-12-04 19:30:01 +0000466Handlers
467^^^^^^^^
468
469:class:`Handler` objects are responsible for dispatching the appropriate log
470messages (based on the log messages' severity) to the handler's specified
471destination. Logger objects can add zero or more handler objects to themselves
472with an :func:`addHandler` method. As an example scenario, an application may
473want to send all log messages to a log file, all log messages of error or higher
474to stdout, and all messages of critical to an email address. This scenario
Christian Heimesc3f30c42008-02-22 16:37:40 +0000475requires three individual handlers where each handler is responsible for sending
Christian Heimes8b0facf2007-12-04 19:30:01 +0000476messages of a specific severity to a specific location.
477
Vinay Sajipf234eb92010-12-12 17:37:27 +0000478The standard library includes quite a few handler types (see
479:ref:`useful-handlers`); the tutorials use mainly :class:`StreamHandler` and
480:class:`FileHandler` in its examples.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000481
482There are very few methods in a handler for application developers to concern
483themselves with. The only handler methods that seem relevant for application
484developers who are using the built-in handler objects (that is, not creating
485custom handlers) are the following configuration methods:
486
487* The :meth:`Handler.setLevel` method, just as in logger objects, specifies the
488 lowest severity that will be dispatched to the appropriate destination. Why
489 are there two :func:`setLevel` methods? The level set in the logger
490 determines which severity of messages it will pass to its handlers. The level
491 set in each handler determines which messages that handler will send on.
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000492
493* :func:`setFormatter` selects a Formatter object for this handler to use.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000494
495* :func:`addFilter` and :func:`removeFilter` respectively configure and
496 deconfigure filter objects on handlers.
497
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000498Application code should not directly instantiate and use instances of
499:class:`Handler`. Instead, the :class:`Handler` class is a base class that
500defines the interface that all handlers should have and establishes some
501default behavior that child classes can use (or override).
Christian Heimes8b0facf2007-12-04 19:30:01 +0000502
503
504Formatters
505^^^^^^^^^^
506
507Formatter objects configure the final order, structure, and contents of the log
Christian Heimesdcca98d2008-02-25 13:19:43 +0000508message. Unlike the base :class:`logging.Handler` class, application code may
Christian Heimes8b0facf2007-12-04 19:30:01 +0000509instantiate formatter classes, although you could likely subclass the formatter
Vinay Sajipa39c5712010-10-25 13:57:39 +0000510if your application needs special behavior. The constructor takes three
511optional arguments -- a message format string, a date format string and a style
512indicator.
513
514.. method:: logging.Formatter.__init__(fmt=None, datefmt=None, style='%')
515
516If there is no message format string, the default is to use the
517raw message. If there is no date format string, the default date format is::
Christian Heimes8b0facf2007-12-04 19:30:01 +0000518
519 %Y-%m-%d %H:%M:%S
520
Vinay Sajipa39c5712010-10-25 13:57:39 +0000521with the milliseconds tacked on at the end. The ``style`` is one of `%`, '{'
522or '$'. If one of these is not specified, then '%' will be used.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000523
Vinay Sajipa39c5712010-10-25 13:57:39 +0000524If the ``style`` is '%', the message format string uses
525``%(<dictionary key>)s`` styled string substitution; the possible keys are
526documented in :ref:`formatter-objects`. If the style is '{', the message format
527string is assumed to be compatible with :meth:`str.format` (using keyword
528arguments), while if the style is '$' then the message format string should
529conform to what is expected by :meth:`string.Template.substitute`.
530
531.. versionchanged:: 3.2
532 Added the ``style`` parameter.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000533
534The following message format string will log the time in a human-readable
535format, the severity of the message, and the contents of the message, in that
536order::
537
538 "%(asctime)s - %(levelname)s - %(message)s"
539
Vinay Sajip40d9a4e2010-08-30 18:10:03 +0000540Formatters use a user-configurable function to convert the creation time of a
541record to a tuple. By default, :func:`time.localtime` is used; to change this
542for a particular formatter instance, set the ``converter`` attribute of the
543instance to a function with the same signature as :func:`time.localtime` or
544:func:`time.gmtime`. To change it for all formatters, for example if you want
545all logging times to be shown in GMT, set the ``converter`` attribute in the
546Formatter class (to ``time.gmtime`` for GMT display).
547
Christian Heimes8b0facf2007-12-04 19:30:01 +0000548
549Configuring Logging
550^^^^^^^^^^^^^^^^^^^
551
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000552Programmers can configure logging in three ways:
553
5541. Creating loggers, handlers, and formatters explicitly using Python
555 code that calls the configuration methods listed above.
5562. Creating a logging config file and reading it using the :func:`fileConfig`
557 function.
5583. Creating a dictionary of configuration information and passing it
559 to the :func:`dictConfig` function.
560
561The following example configures a very simple logger, a console
562handler, and a simple formatter using Python code::
Christian Heimes8b0facf2007-12-04 19:30:01 +0000563
564 import logging
565
566 # create logger
567 logger = logging.getLogger("simple_example")
568 logger.setLevel(logging.DEBUG)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000569
Christian Heimes8b0facf2007-12-04 19:30:01 +0000570 # create console handler and set level to debug
571 ch = logging.StreamHandler()
572 ch.setLevel(logging.DEBUG)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000573
Christian Heimes8b0facf2007-12-04 19:30:01 +0000574 # create formatter
575 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000576
Christian Heimes8b0facf2007-12-04 19:30:01 +0000577 # add formatter to ch
578 ch.setFormatter(formatter)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000579
Christian Heimes8b0facf2007-12-04 19:30:01 +0000580 # add ch to logger
581 logger.addHandler(ch)
582
583 # "application" code
584 logger.debug("debug message")
585 logger.info("info message")
586 logger.warn("warn message")
587 logger.error("error message")
588 logger.critical("critical message")
589
590Running this module from the command line produces the following output::
591
592 $ python simple_logging_module.py
593 2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
594 2005-03-19 15:10:26,620 - simple_example - INFO - info message
595 2005-03-19 15:10:26,695 - simple_example - WARNING - warn message
596 2005-03-19 15:10:26,697 - simple_example - ERROR - error message
597 2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message
598
599The following Python module creates a logger, handler, and formatter nearly
600identical to those in the example listed above, with the only difference being
601the names of the objects::
602
603 import logging
604 import logging.config
605
606 logging.config.fileConfig("logging.conf")
607
608 # create logger
609 logger = logging.getLogger("simpleExample")
610
611 # "application" code
612 logger.debug("debug message")
613 logger.info("info message")
614 logger.warn("warn message")
615 logger.error("error message")
616 logger.critical("critical message")
617
618Here is the logging.conf file::
619
620 [loggers]
621 keys=root,simpleExample
622
623 [handlers]
624 keys=consoleHandler
625
626 [formatters]
627 keys=simpleFormatter
628
629 [logger_root]
630 level=DEBUG
631 handlers=consoleHandler
632
633 [logger_simpleExample]
634 level=DEBUG
635 handlers=consoleHandler
636 qualname=simpleExample
637 propagate=0
638
639 [handler_consoleHandler]
640 class=StreamHandler
641 level=DEBUG
642 formatter=simpleFormatter
643 args=(sys.stdout,)
644
645 [formatter_simpleFormatter]
646 format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
647 datefmt=
648
649The output is nearly identical to that of the non-config-file-based example::
650
651 $ python simple_logging_config.py
652 2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
653 2005-03-19 15:38:55,979 - simpleExample - INFO - info message
654 2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
655 2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
656 2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message
657
658You can see that the config file approach has a few advantages over the Python
659code approach, mainly separation of configuration and code and the ability of
660noncoders to easily modify the logging properties.
661
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000662Note that the class names referenced in config files need to be either relative
663to the logging module, or absolute values which can be resolved using normal
Senthil Kumaran46a48be2010-10-15 13:10:10 +0000664import mechanisms. Thus, you could use either
665:class:`handlers.WatchedFileHandler` (relative to the logging module) or
666``mypackage.mymodule.MyHandler`` (for a class defined in package ``mypackage``
667and module ``mymodule``, where ``mypackage`` is available on the Python import
668path).
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000669
Benjamin Peterson56894b52010-06-28 00:16:12 +0000670In Python 3.2, a new means of configuring logging has been introduced, using
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000671dictionaries to hold configuration information. This provides a superset of the
672functionality of the config-file-based approach outlined above, and is the
673recommended configuration method for new applications and deployments. Because
674a Python dictionary is used to hold configuration information, and since you
675can populate that dictionary using different means, you have more options for
676configuration. For example, you can use a configuration file in JSON format,
677or, if you have access to YAML processing functionality, a file in YAML
678format, to populate the configuration dictionary. Or, of course, you can
679construct the dictionary in Python code, receive it in pickled form over a
680socket, or use whatever approach makes sense for your application.
681
682Here's an example of the same configuration as above, in YAML format for
683the new dictionary-based approach::
684
685 version: 1
686 formatters:
687 simple:
688 format: format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
689 handlers:
690 console:
691 class: logging.StreamHandler
692 level: DEBUG
693 formatter: simple
694 stream: ext://sys.stdout
695 loggers:
696 simpleExample:
697 level: DEBUG
698 handlers: [console]
699 propagate: no
700 root:
701 level: DEBUG
702 handlers: [console]
703
704For more information about logging using a dictionary, see
705:ref:`logging-config-api`.
706
Vinay Sajipf234eb92010-12-12 17:37:27 +0000707What happens if no configuration is provided
708^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
709
710If no logging configuration is provided, it is possible to have a situation
711where a logging event needs to be output, but no handlers can be found to
712output the event. The behaviour of the logging package in these
713circumstances is dependent on the Python version.
714
715For versions of Python prior to 3.2, the behaviour is as follows:
716
717* If *logging.raiseExceptions* is *False* (production mode), the event is
718 silently dropped.
719
720* If *logging.raiseExceptions* is *True* (development mode), a message
721 "No handlers could be found for logger X.Y.Z" is printed once.
722
723In Python 3.2 and later, the behaviour is as follows:
724
725* The event is output using a 'handler of last resort", stored in
726 ``logging.lastResort``. This internal handler is not associated with any
727 logger, and acts like a :class:`StreamHandler` which writes the event
728 description message to the current value of ``sys.stderr`` (therefore
729 respecting any redirections which may be in effect). No formatting is
730 done on the message - just the bare event description message is printed.
731 The handler's level is set to ``WARNING``, so all events at this and
732 greater severities will be output.
733
734To obtain the pre-3.2 behaviour, ``logging.lastResort`` can be set to *None*.
735
Vinay Sajip26a2d5e2009-01-10 13:37:26 +0000736.. _library-config:
Vinay Sajip30bf1222009-01-10 19:23:34 +0000737
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000738Configuring Logging for a Library
739^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
740
Vinay Sajipf234eb92010-12-12 17:37:27 +0000741When developing a library which uses logging, you should take care to
742document how the library uses logging - for example, the names of loggers
743used. Some consideration also needs to be given to its logging configuration.
744If the using application does not use logging, and library code makes logging
745calls, then (as described in the previous section) events of severity
746``WARNING`` and greater will be printed to ``sys.stderr``. This is regarded as
747the best default behaviour.
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000748
Vinay Sajipf234eb92010-12-12 17:37:27 +0000749If for some reason you *don't* want these messages printed in the absence of
750any logging configuration, you can attach a do-nothing handler to the top-level
751logger for your library. This avoids the message being printed, since a handler
752will be always be found for the library's events: it just doesn't produce any
753output. If the library user configures logging for application use, presumably
754that configuration will add some handlers, and if levels are suitably
755configured then logging calls made in library code will send output to those
756handlers, as normal.
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000757
Vinay Sajipf234eb92010-12-12 17:37:27 +0000758A do-nothing handler is included in the logging package: :class:`NullHandler`
759(since Python 3.1). An instance of this handler could be added to the top-level
760logger of the logging namespace used by the library (*if* you want to prevent
761your library's logged events being output to ``sys.stderr`` in the absence of
762logging configuration). If all logging by a library *foo* is done using loggers
763with names matching 'foo.x', 'foo.x.y', etc. then the code::
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000764
765 import logging
Vinay Sajipf234eb92010-12-12 17:37:27 +0000766 logging.getLogger('foo').addHandler(logging.NullHandler())
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000767
768should have the desired effect. If an organisation produces a number of
Vinay Sajipf234eb92010-12-12 17:37:27 +0000769libraries, then the logger name specified can be 'orgname.foo' rather than
770just 'foo'.
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000771
Vinay Sajip76ca3b42010-09-27 13:53:47 +0000772**PLEASE NOTE:** It is strongly advised that you *do not add any handlers other
773than* :class:`NullHandler` *to your library's loggers*. This is because the
774configuration of handlers is the prerogative of the application developer who
775uses your library. The application developer knows their target audience and
776what handlers are most appropriate for their application: if you add handlers
777"under the hood", you might well interfere with their ability to carry out
778unit tests and deliver logs which suit their requirements.
779
Christian Heimes8b0facf2007-12-04 19:30:01 +0000780
781Logging Levels
782--------------
783
Georg Brandl116aa622007-08-15 14:28:22 +0000784The numeric values of logging levels are given in the following table. These are
785primarily of interest if you want to define your own levels, and need them to
786have specific values relative to the predefined levels. If you define a level
787with the same numeric value, it overwrites the predefined value; the predefined
788name is lost.
789
790+--------------+---------------+
791| Level | Numeric value |
792+==============+===============+
793| ``CRITICAL`` | 50 |
794+--------------+---------------+
795| ``ERROR`` | 40 |
796+--------------+---------------+
797| ``WARNING`` | 30 |
798+--------------+---------------+
799| ``INFO`` | 20 |
800+--------------+---------------+
801| ``DEBUG`` | 10 |
802+--------------+---------------+
803| ``NOTSET`` | 0 |
804+--------------+---------------+
805
806Levels can also be associated with loggers, being set either by the developer or
807through loading a saved logging configuration. When a logging method is called
808on a logger, the logger compares its own level with the level associated with
809the method call. If the logger's level is higher than the method call's, no
810logging message is actually generated. This is the basic mechanism controlling
811the verbosity of logging output.
812
813Logging messages are encoded as instances of the :class:`LogRecord` class. When
814a logger decides to actually log an event, a :class:`LogRecord` instance is
815created from the logging message.
816
817Logging messages are subjected to a dispatch mechanism through the use of
818:dfn:`handlers`, which are instances of subclasses of the :class:`Handler`
819class. Handlers are responsible for ensuring that a logged message (in the form
820of a :class:`LogRecord`) ends up in a particular location (or set of locations)
821which is useful for the target audience for that message (such as end users,
822support desk staff, system administrators, developers). Handlers are passed
823:class:`LogRecord` instances intended for particular destinations. Each logger
824can have zero, one or more handlers associated with it (via the
825:meth:`addHandler` method of :class:`Logger`). In addition to any handlers
826directly associated with a logger, *all handlers associated with all ancestors
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000827of the logger* are called to dispatch the message (unless the *propagate* flag
828for a logger is set to a false value, at which point the passing to ancestor
829handlers stops).
Georg Brandl116aa622007-08-15 14:28:22 +0000830
831Just as for loggers, handlers can have levels associated with them. A handler's
832level acts as a filter in the same way as a logger's level does. If a handler
833decides to actually dispatch an event, the :meth:`emit` method is used to send
834the message to its destination. Most user-defined subclasses of :class:`Handler`
835will need to override this :meth:`emit`.
836
Vinay Sajipc8c8c692010-09-17 10:09:04 +0000837.. _custom-levels:
838
839Custom Levels
840^^^^^^^^^^^^^
841
842Defining your own levels is possible, but should not be necessary, as the
843existing levels have been chosen on the basis of practical experience.
844However, if you are convinced that you need custom levels, great care should
845be exercised when doing this, and it is possibly *a very bad idea to define
846custom levels if you are developing a library*. That's because if multiple
847library authors all define their own custom levels, there is a chance that
848the logging output from such multiple libraries used together will be
849difficult for the using developer to control and/or interpret, because a
850given numeric value might mean different things for different libraries.
851
852
Vinay Sajipf234eb92010-12-12 17:37:27 +0000853.. _useful-handlers:
854
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000855Useful Handlers
856---------------
857
Georg Brandl116aa622007-08-15 14:28:22 +0000858In addition to the base :class:`Handler` class, many useful subclasses are
859provided:
860
Vinay Sajip121a1c42010-09-08 10:46:15 +0000861#. :class:`StreamHandler` instances send messages to streams (file-like
Georg Brandl116aa622007-08-15 14:28:22 +0000862 objects).
863
Vinay Sajip121a1c42010-09-08 10:46:15 +0000864#. :class:`FileHandler` instances send messages to disk files.
Georg Brandl116aa622007-08-15 14:28:22 +0000865
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000866.. module:: logging.handlers
Vinay Sajip30bf1222009-01-10 19:23:34 +0000867
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000868#. :class:`BaseRotatingHandler` is the base class for handlers that
869 rotate log files at a certain point. It is not meant to be instantiated
870 directly. Instead, use :class:`RotatingFileHandler` or
871 :class:`TimedRotatingFileHandler`.
Georg Brandl116aa622007-08-15 14:28:22 +0000872
Vinay Sajip121a1c42010-09-08 10:46:15 +0000873#. :class:`RotatingFileHandler` instances send messages to disk
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000874 files, with support for maximum log file sizes and log file rotation.
Georg Brandl116aa622007-08-15 14:28:22 +0000875
Vinay Sajip121a1c42010-09-08 10:46:15 +0000876#. :class:`TimedRotatingFileHandler` instances send messages to
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000877 disk files, rotating the log file at certain timed intervals.
Georg Brandl116aa622007-08-15 14:28:22 +0000878
Vinay Sajip121a1c42010-09-08 10:46:15 +0000879#. :class:`SocketHandler` instances send messages to TCP/IP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000880 sockets.
Georg Brandl116aa622007-08-15 14:28:22 +0000881
Vinay Sajip121a1c42010-09-08 10:46:15 +0000882#. :class:`DatagramHandler` instances send messages to UDP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000883 sockets.
Georg Brandl116aa622007-08-15 14:28:22 +0000884
Vinay Sajip121a1c42010-09-08 10:46:15 +0000885#. :class:`SMTPHandler` instances send messages to a designated
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000886 email address.
Georg Brandl116aa622007-08-15 14:28:22 +0000887
Vinay Sajip121a1c42010-09-08 10:46:15 +0000888#. :class:`SysLogHandler` instances send messages to a Unix
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000889 syslog daemon, possibly on a remote machine.
Georg Brandl116aa622007-08-15 14:28:22 +0000890
Vinay Sajip121a1c42010-09-08 10:46:15 +0000891#. :class:`NTEventLogHandler` instances send messages to a
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000892 Windows NT/2000/XP event log.
Georg Brandl116aa622007-08-15 14:28:22 +0000893
Vinay Sajip121a1c42010-09-08 10:46:15 +0000894#. :class:`MemoryHandler` instances send messages to a buffer
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000895 in memory, which is flushed whenever specific criteria are met.
Georg Brandl116aa622007-08-15 14:28:22 +0000896
Vinay Sajip121a1c42010-09-08 10:46:15 +0000897#. :class:`HTTPHandler` instances send messages to an HTTP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000898 server using either ``GET`` or ``POST`` semantics.
Georg Brandl116aa622007-08-15 14:28:22 +0000899
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000900#. :class:`WatchedFileHandler` instances watch the file they are
901 logging to. If the file changes, it is closed and reopened using the file
902 name. This handler is only useful on Unix-like systems; Windows does not
903 support the underlying mechanism used.
Vinay Sajip30bf1222009-01-10 19:23:34 +0000904
Vinay Sajip121a1c42010-09-08 10:46:15 +0000905#. :class:`QueueHandler` instances send messages to a queue, such as
906 those implemented in the :mod:`queue` or :mod:`multiprocessing` modules.
907
Vinay Sajip30bf1222009-01-10 19:23:34 +0000908.. currentmodule:: logging
909
Georg Brandlf9734072008-12-07 15:30:06 +0000910#. :class:`NullHandler` instances do nothing with error messages. They are used
911 by library developers who want to use logging, but want to avoid the "No
912 handlers could be found for logger XXX" message which can be displayed if
Vinay Sajip26a2d5e2009-01-10 13:37:26 +0000913 the library user has not configured logging. See :ref:`library-config` for
914 more information.
Georg Brandlf9734072008-12-07 15:30:06 +0000915
916.. versionadded:: 3.1
Georg Brandl1eb40bc2010-12-03 15:30:09 +0000917 The :class:`NullHandler` class.
Georg Brandlf9734072008-12-07 15:30:06 +0000918
Vinay Sajip121a1c42010-09-08 10:46:15 +0000919.. versionadded:: 3.2
Vinay Sajipa18b9592010-12-12 13:20:55 +0000920 The :class:`~logging.handlers.QueueHandler` class.
Vinay Sajip121a1c42010-09-08 10:46:15 +0000921
Vinay Sajipa17775f2008-12-30 07:32:59 +0000922The :class:`NullHandler`, :class:`StreamHandler` and :class:`FileHandler`
923classes are defined in the core logging package. The other handlers are
924defined in a sub- module, :mod:`logging.handlers`. (There is also another
925sub-module, :mod:`logging.config`, for configuration functionality.)
Georg Brandl116aa622007-08-15 14:28:22 +0000926
927Logged messages are formatted for presentation through instances of the
928:class:`Formatter` class. They are initialized with a format string suitable for
929use with the % operator and a dictionary.
930
931For formatting multiple messages in a batch, instances of
932:class:`BufferingFormatter` can be used. In addition to the format string (which
933is applied to each message in the batch), there is provision for header and
934trailer format strings.
935
936When filtering based on logger level and/or handler level is not enough,
937instances of :class:`Filter` can be added to both :class:`Logger` and
938:class:`Handler` instances (through their :meth:`addFilter` method). Before
939deciding to process a message further, both loggers and handlers consult all
940their filters for permission. If any filter returns a false value, the message
941is not processed further.
942
943The basic :class:`Filter` functionality allows filtering by specific logger
944name. If this feature is used, messages sent to the named logger and its
945children are allowed through the filter, and all others dropped.
946
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000947Module-Level Functions
948----------------------
949
Georg Brandl116aa622007-08-15 14:28:22 +0000950In addition to the classes described above, there are a number of module- level
951functions.
952
953
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000954.. function:: getLogger(name=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000955
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000956 Return a logger with the specified name or, if name is ``None``, return a
Georg Brandl116aa622007-08-15 14:28:22 +0000957 logger which is the root logger of the hierarchy. If specified, the name is
958 typically a dot-separated hierarchical name like *"a"*, *"a.b"* or *"a.b.c.d"*.
959 Choice of these names is entirely up to the developer who is using logging.
960
961 All calls to this function with a given name return the same logger instance.
962 This means that logger instances never need to be passed between different parts
963 of an application.
964
965
966.. function:: getLoggerClass()
967
968 Return either the standard :class:`Logger` class, or the last class passed to
969 :func:`setLoggerClass`. This function may be called from within a new class
970 definition, to ensure that installing a customised :class:`Logger` class will
971 not undo customisations already applied by other code. For example::
972
973 class MyLogger(logging.getLoggerClass()):
974 # ... override behaviour here
975
976
Vinay Sajip61561522010-12-03 11:50:38 +0000977.. function:: getLogRecordFactory()
978
979 Return a callable which is used to create a :class:`LogRecord`.
980
981 .. versionadded:: 3.2
Vinay Sajip61561522010-12-03 11:50:38 +0000982 This function has been provided, along with :func:`setLogRecordFactory`,
983 to allow developers more control over how the :class:`LogRecord`
984 representing a logging event is constructed.
985
986 See :func:`setLogRecordFactory` for more information about the how the
987 factory is called.
988
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000989.. function:: debug(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000990
991 Logs a message with level :const:`DEBUG` on the root logger. The *msg* is the
992 message format string, and the *args* are the arguments which are merged into
993 *msg* using the string formatting operator. (Note that this means that you can
994 use keywords in the format string, together with a single dictionary argument.)
995
Vinay Sajip8593ae62010-11-14 21:33:04 +0000996 There are three keyword arguments in *kwargs* which are inspected: *exc_info*
Georg Brandl116aa622007-08-15 14:28:22 +0000997 which, if it does not evaluate as false, causes exception information to be
998 added to the logging message. If an exception tuple (in the format returned by
999 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
1000 is called to get the exception information.
1001
Vinay Sajip8593ae62010-11-14 21:33:04 +00001002 The second optional keyword argument is *stack_info*, which defaults to
1003 False. If specified as True, stack information is added to the logging
1004 message, including the actual logging call. Note that this is not the same
1005 stack information as that displayed through specifying *exc_info*: The
1006 former is stack frames from the bottom of the stack up to the logging call
1007 in the current thread, whereas the latter is information about stack frames
1008 which have been unwound, following an exception, while searching for
1009 exception handlers.
1010
1011 You can specify *stack_info* independently of *exc_info*, e.g. to just show
1012 how you got to a certain point in your code, even when no exceptions were
1013 raised. The stack frames are printed following a header line which says::
1014
1015 Stack (most recent call last):
1016
1017 This mimics the `Traceback (most recent call last):` which is used when
1018 displaying exception frames.
1019
1020 The third optional keyword argument is *extra* which can be used to pass a
Georg Brandl116aa622007-08-15 14:28:22 +00001021 dictionary which is used to populate the __dict__ of the LogRecord created for
1022 the logging event with user-defined attributes. These custom attributes can then
1023 be used as you like. For example, they could be incorporated into logged
1024 messages. For example::
1025
1026 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
1027 logging.basicConfig(format=FORMAT)
1028 d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
1029 logging.warning("Protocol problem: %s", "connection reset", extra=d)
1030
Vinay Sajip4039aff2010-09-11 10:25:28 +00001031 would print something like::
Georg Brandl116aa622007-08-15 14:28:22 +00001032
1033 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
1034
1035 The keys in the dictionary passed in *extra* should not clash with the keys used
1036 by the logging system. (See the :class:`Formatter` documentation for more
1037 information on which keys are used by the logging system.)
1038
1039 If you choose to use these attributes in logged messages, you need to exercise
1040 some care. In the above example, for instance, the :class:`Formatter` has been
1041 set up with a format string which expects 'clientip' and 'user' in the attribute
1042 dictionary of the LogRecord. If these are missing, the message will not be
1043 logged because a string formatting exception will occur. So in this case, you
1044 always need to pass the *extra* dictionary with these keys.
1045
1046 While this might be annoying, this feature is intended for use in specialized
1047 circumstances, such as multi-threaded servers where the same code executes in
1048 many contexts, and interesting conditions which arise are dependent on this
1049 context (such as remote client IP address and authenticated user name, in the
1050 above example). In such circumstances, it is likely that specialized
1051 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
1052
Vinay Sajip8593ae62010-11-14 21:33:04 +00001053 .. versionadded:: 3.2
1054 The *stack_info* parameter was added.
Georg Brandl116aa622007-08-15 14:28:22 +00001055
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001056.. function:: info(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001057
1058 Logs a message with level :const:`INFO` on the root logger. The arguments are
1059 interpreted as for :func:`debug`.
1060
1061
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001062.. function:: warning(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001063
1064 Logs a message with level :const:`WARNING` on the root logger. The arguments are
1065 interpreted as for :func:`debug`.
1066
1067
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001068.. function:: error(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001069
1070 Logs a message with level :const:`ERROR` on the root logger. The arguments are
1071 interpreted as for :func:`debug`.
1072
1073
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001074.. function:: critical(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001075
1076 Logs a message with level :const:`CRITICAL` on the root logger. The arguments
1077 are interpreted as for :func:`debug`.
1078
1079
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001080.. function:: exception(msg, *args)
Georg Brandl116aa622007-08-15 14:28:22 +00001081
1082 Logs a message with level :const:`ERROR` on the root logger. The arguments are
1083 interpreted as for :func:`debug`. Exception info is added to the logging
1084 message. This function should only be called from an exception handler.
1085
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001086.. function:: log(level, msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001087
1088 Logs a message with level *level* on the root logger. The other arguments are
1089 interpreted as for :func:`debug`.
1090
Vinay Sajipc8c8c692010-09-17 10:09:04 +00001091 PLEASE NOTE: The above module-level functions which delegate to the root
1092 logger should *not* be used in threads, in versions of Python earlier than
1093 2.7.1 and 3.2, unless at least one handler has been added to the root
1094 logger *before* the threads are started. These convenience functions call
1095 :func:`basicConfig` to ensure that at least one handler is available; in
1096 earlier versions of Python, this can (under rare circumstances) lead to
1097 handlers being added multiple times to the root logger, which can in turn
1098 lead to multiple messages for the same event.
Georg Brandl116aa622007-08-15 14:28:22 +00001099
1100.. function:: disable(lvl)
1101
1102 Provides an overriding level *lvl* for all loggers which takes precedence over
1103 the logger's own level. When the need arises to temporarily throttle logging
Benjamin Peterson886af962010-03-21 23:13:07 +00001104 output down across the whole application, this function can be useful. Its
1105 effect is to disable all logging calls of severity *lvl* and below, so that
1106 if you call it with a value of INFO, then all INFO and DEBUG events would be
1107 discarded, whereas those of severity WARNING and above would be processed
1108 according to the logger's effective level.
Georg Brandl116aa622007-08-15 14:28:22 +00001109
1110
1111.. function:: addLevelName(lvl, levelName)
1112
1113 Associates level *lvl* with text *levelName* in an internal dictionary, which is
1114 used to map numeric levels to a textual representation, for example when a
1115 :class:`Formatter` formats a message. This function can also be used to define
1116 your own levels. The only constraints are that all levels used must be
1117 registered using this function, levels should be positive integers and they
1118 should increase in increasing order of severity.
1119
Vinay Sajipc8c8c692010-09-17 10:09:04 +00001120 NOTE: If you are thinking of defining your own levels, please see the section
1121 on :ref:`custom-levels`.
Georg Brandl116aa622007-08-15 14:28:22 +00001122
1123.. function:: getLevelName(lvl)
1124
1125 Returns the textual representation of logging level *lvl*. If the level is one
1126 of the predefined levels :const:`CRITICAL`, :const:`ERROR`, :const:`WARNING`,
1127 :const:`INFO` or :const:`DEBUG` then you get the corresponding string. If you
1128 have associated levels with names using :func:`addLevelName` then the name you
1129 have associated with *lvl* is returned. If a numeric value corresponding to one
1130 of the defined levels is passed in, the corresponding string representation is
1131 returned. Otherwise, the string "Level %s" % lvl is returned.
1132
1133
1134.. function:: makeLogRecord(attrdict)
1135
1136 Creates and returns a new :class:`LogRecord` instance whose attributes are
1137 defined by *attrdict*. This function is useful for taking a pickled
1138 :class:`LogRecord` attribute dictionary, sent over a socket, and reconstituting
1139 it as a :class:`LogRecord` instance at the receiving end.
1140
1141
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001142.. function:: basicConfig(**kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001143
1144 Does basic configuration for the logging system by creating a
1145 :class:`StreamHandler` with a default :class:`Formatter` and adding it to the
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00001146 root logger. The functions :func:`debug`, :func:`info`, :func:`warning`,
Georg Brandl116aa622007-08-15 14:28:22 +00001147 :func:`error` and :func:`critical` will call :func:`basicConfig` automatically
1148 if no handlers are defined for the root logger.
1149
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00001150 This function does nothing if the root logger already has handlers
1151 configured for it.
1152
Vinay Sajipc8c8c692010-09-17 10:09:04 +00001153 PLEASE NOTE: This function should be called from the main thread
1154 before other threads are started. In versions of Python prior to
1155 2.7.1 and 3.2, if this function is called from multiple threads,
1156 it is possible (in rare circumstances) that a handler will be added
1157 to the root logger more than once, leading to unexpected results
1158 such as messages being duplicated in the log.
1159
Georg Brandl116aa622007-08-15 14:28:22 +00001160 The following keyword arguments are supported.
1161
1162 +--------------+---------------------------------------------+
1163 | Format | Description |
1164 +==============+=============================================+
1165 | ``filename`` | Specifies that a FileHandler be created, |
1166 | | using the specified filename, rather than a |
1167 | | StreamHandler. |
1168 +--------------+---------------------------------------------+
1169 | ``filemode`` | Specifies the mode to open the file, if |
1170 | | filename is specified (if filemode is |
1171 | | unspecified, it defaults to 'a'). |
1172 +--------------+---------------------------------------------+
1173 | ``format`` | Use the specified format string for the |
1174 | | handler. |
1175 +--------------+---------------------------------------------+
1176 | ``datefmt`` | Use the specified date/time format. |
1177 +--------------+---------------------------------------------+
Vinay Sajipc5b27302010-10-31 14:59:16 +00001178 | ``style`` | If ``format`` is specified, use this style |
1179 | | for the format string. One of '%', '{' or |
1180 | | '$' for %-formatting, :meth:`str.format` or |
1181 | | :class:`string.Template` respectively, and |
1182 | | defaulting to '%' if not specified. |
1183 +--------------+---------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001184 | ``level`` | Set the root logger level to the specified |
1185 | | level. |
1186 +--------------+---------------------------------------------+
1187 | ``stream`` | Use the specified stream to initialize the |
1188 | | StreamHandler. Note that this argument is |
1189 | | incompatible with 'filename' - if both are |
1190 | | present, 'stream' is ignored. |
1191 +--------------+---------------------------------------------+
1192
Vinay Sajipc5b27302010-10-31 14:59:16 +00001193 .. versionchanged:: 3.2
1194 The ``style`` argument was added.
1195
1196
Georg Brandl116aa622007-08-15 14:28:22 +00001197.. function:: shutdown()
1198
1199 Informs the logging system to perform an orderly shutdown by flushing and
Christian Heimesb186d002008-03-18 15:15:01 +00001200 closing all handlers. This should be called at application exit and no
1201 further use of the logging system should be made after this call.
Georg Brandl116aa622007-08-15 14:28:22 +00001202
1203
1204.. function:: setLoggerClass(klass)
1205
1206 Tells the logging system to use the class *klass* when instantiating a logger.
1207 The class should define :meth:`__init__` such that only a name argument is
1208 required, and the :meth:`__init__` should call :meth:`Logger.__init__`. This
1209 function is typically called before any loggers are instantiated by applications
1210 which need to use custom logger behavior.
1211
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001212
Vinay Sajip61561522010-12-03 11:50:38 +00001213.. function:: setLogRecordFactory(factory)
1214
1215 Set a callable which is used to create a :class:`LogRecord`.
1216
1217 :param factory: The factory callable to be used to instantiate a log record.
1218
1219 .. versionadded:: 3.2
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001220 This function has been provided, along with :func:`getLogRecordFactory`, to
1221 allow developers more control over how the :class:`LogRecord` representing
1222 a logging event is constructed.
Vinay Sajip61561522010-12-03 11:50:38 +00001223
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001224 The factory has the following signature:
Vinay Sajip61561522010-12-03 11:50:38 +00001225
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001226 ``factory(name, level, fn, lno, msg, args, exc_info, func=None, sinfo=None, \*\*kwargs)``
Vinay Sajip61561522010-12-03 11:50:38 +00001227
1228 :name: The logger name.
1229 :level: The logging level (numeric).
1230 :fn: The full pathname of the file where the logging call was made.
1231 :lno: The line number in the file where the logging call was made.
1232 :msg: The logging message.
1233 :args: The arguments for the logging message.
1234 :exc_info: An exception tuple, or None.
1235 :func: The name of the function or method which invoked the logging
1236 call.
1237 :sinfo: A stack traceback such as is provided by
1238 :func:`traceback.print_stack`, showing the call hierarchy.
1239 :kwargs: Additional keyword arguments.
Georg Brandl116aa622007-08-15 14:28:22 +00001240
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001241
Georg Brandl116aa622007-08-15 14:28:22 +00001242.. seealso::
1243
1244 :pep:`282` - A Logging System
1245 The proposal which described this feature for inclusion in the Python standard
1246 library.
1247
Christian Heimes255f53b2007-12-08 15:33:56 +00001248 `Original Python logging package <http://www.red-dove.com/python_logging.html>`_
Georg Brandl116aa622007-08-15 14:28:22 +00001249 This is the original source for the :mod:`logging` package. The version of the
1250 package available from this site is suitable for use with Python 1.5.2, 2.1.x
1251 and 2.2.x, which do not include the :mod:`logging` package in the standard
1252 library.
1253
Vinay Sajip4039aff2010-09-11 10:25:28 +00001254.. _logger:
Georg Brandl116aa622007-08-15 14:28:22 +00001255
1256Logger Objects
1257--------------
1258
1259Loggers have the following attributes and methods. Note that Loggers are never
1260instantiated directly, but always through the module-level function
1261``logging.getLogger(name)``.
1262
Vinay Sajip0258ce82010-09-22 20:34:53 +00001263.. class:: Logger
Georg Brandl116aa622007-08-15 14:28:22 +00001264
1265.. attribute:: Logger.propagate
1266
1267 If this evaluates to false, logging messages are not passed by this logger or by
Benjamin Peterson22005fc2010-04-11 16:25:06 +00001268 its child loggers to the handlers of higher level (ancestor) loggers. The
1269 constructor sets this attribute to 1.
Georg Brandl116aa622007-08-15 14:28:22 +00001270
1271
1272.. method:: Logger.setLevel(lvl)
1273
1274 Sets the threshold for this logger to *lvl*. Logging messages which are less
1275 severe than *lvl* will be ignored. When a logger is created, the level is set to
1276 :const:`NOTSET` (which causes all messages to be processed when the logger is
1277 the root logger, or delegation to the parent when the logger is a non-root
1278 logger). Note that the root logger is created with level :const:`WARNING`.
1279
1280 The term "delegation to the parent" means that if a logger has a level of
1281 NOTSET, its chain of ancestor loggers is traversed until either an ancestor with
1282 a level other than NOTSET is found, or the root is reached.
1283
1284 If an ancestor is found with a level other than NOTSET, then that ancestor's
1285 level is treated as the effective level of the logger where the ancestor search
1286 began, and is used to determine how a logging event is handled.
1287
1288 If the root is reached, and it has a level of NOTSET, then all messages will be
1289 processed. Otherwise, the root's level will be used as the effective level.
1290
1291
1292.. method:: Logger.isEnabledFor(lvl)
1293
1294 Indicates if a message of severity *lvl* would be processed by this logger.
1295 This method checks first the module-level level set by
1296 ``logging.disable(lvl)`` and then the logger's effective level as determined
1297 by :meth:`getEffectiveLevel`.
1298
1299
1300.. method:: Logger.getEffectiveLevel()
1301
1302 Indicates the effective level for this logger. If a value other than
1303 :const:`NOTSET` has been set using :meth:`setLevel`, it is returned. Otherwise,
1304 the hierarchy is traversed towards the root until a value other than
1305 :const:`NOTSET` is found, and that value is returned.
1306
1307
Benjamin Peterson22005fc2010-04-11 16:25:06 +00001308.. method:: Logger.getChild(suffix)
1309
1310 Returns a logger which is a descendant to this logger, as determined by the suffix.
1311 Thus, ``logging.getLogger('abc').getChild('def.ghi')`` would return the same
1312 logger as would be returned by ``logging.getLogger('abc.def.ghi')``. This is a
1313 convenience method, useful when the parent logger is named using e.g. ``__name__``
1314 rather than a literal string.
1315
1316 .. versionadded:: 3.2
1317
Georg Brandl67b21b72010-08-17 15:07:14 +00001318
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001319.. method:: Logger.debug(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001320
1321 Logs a message with level :const:`DEBUG` on this logger. The *msg* is the
1322 message format string, and the *args* are the arguments which are merged into
1323 *msg* using the string formatting operator. (Note that this means that you can
1324 use keywords in the format string, together with a single dictionary argument.)
1325
Vinay Sajip8593ae62010-11-14 21:33:04 +00001326 There are three keyword arguments in *kwargs* which are inspected: *exc_info*
Georg Brandl116aa622007-08-15 14:28:22 +00001327 which, if it does not evaluate as false, causes exception information to be
1328 added to the logging message. If an exception tuple (in the format returned by
1329 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
1330 is called to get the exception information.
1331
Vinay Sajip8593ae62010-11-14 21:33:04 +00001332 The second optional keyword argument is *stack_info*, which defaults to
1333 False. If specified as True, stack information is added to the logging
1334 message, including the actual logging call. Note that this is not the same
1335 stack information as that displayed through specifying *exc_info*: The
1336 former is stack frames from the bottom of the stack up to the logging call
1337 in the current thread, whereas the latter is information about stack frames
1338 which have been unwound, following an exception, while searching for
1339 exception handlers.
1340
1341 You can specify *stack_info* independently of *exc_info*, e.g. to just show
1342 how you got to a certain point in your code, even when no exceptions were
1343 raised. The stack frames are printed following a header line which says::
1344
1345 Stack (most recent call last):
1346
1347 This mimics the `Traceback (most recent call last):` which is used when
1348 displaying exception frames.
1349
1350 The third keyword argument is *extra* which can be used to pass a
Georg Brandl116aa622007-08-15 14:28:22 +00001351 dictionary which is used to populate the __dict__ of the LogRecord created for
1352 the logging event with user-defined attributes. These custom attributes can then
1353 be used as you like. For example, they could be incorporated into logged
1354 messages. For example::
1355
1356 FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
1357 logging.basicConfig(format=FORMAT)
Georg Brandl9afde1c2007-11-01 20:32:30 +00001358 d = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
Georg Brandl116aa622007-08-15 14:28:22 +00001359 logger = logging.getLogger("tcpserver")
1360 logger.warning("Protocol problem: %s", "connection reset", extra=d)
1361
1362 would print something like ::
1363
1364 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
1365
1366 The keys in the dictionary passed in *extra* should not clash with the keys used
1367 by the logging system. (See the :class:`Formatter` documentation for more
1368 information on which keys are used by the logging system.)
1369
1370 If you choose to use these attributes in logged messages, you need to exercise
1371 some care. In the above example, for instance, the :class:`Formatter` has been
1372 set up with a format string which expects 'clientip' and 'user' in the attribute
1373 dictionary of the LogRecord. If these are missing, the message will not be
1374 logged because a string formatting exception will occur. So in this case, you
1375 always need to pass the *extra* dictionary with these keys.
1376
1377 While this might be annoying, this feature is intended for use in specialized
1378 circumstances, such as multi-threaded servers where the same code executes in
1379 many contexts, and interesting conditions which arise are dependent on this
1380 context (such as remote client IP address and authenticated user name, in the
1381 above example). In such circumstances, it is likely that specialized
1382 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
1383
Vinay Sajip8593ae62010-11-14 21:33:04 +00001384 .. versionadded:: 3.2
1385 The *stack_info* parameter was added.
1386
Georg Brandl116aa622007-08-15 14:28:22 +00001387
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001388.. method:: Logger.info(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001389
1390 Logs a message with level :const:`INFO` on this logger. The arguments are
1391 interpreted as for :meth:`debug`.
1392
1393
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001394.. method:: Logger.warning(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001395
1396 Logs a message with level :const:`WARNING` on this logger. The arguments are
1397 interpreted as for :meth:`debug`.
1398
1399
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001400.. method:: Logger.error(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001401
1402 Logs a message with level :const:`ERROR` on this logger. The arguments are
1403 interpreted as for :meth:`debug`.
1404
1405
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001406.. method:: Logger.critical(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001407
1408 Logs a message with level :const:`CRITICAL` on this logger. The arguments are
1409 interpreted as for :meth:`debug`.
1410
1411
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001412.. method:: Logger.log(lvl, msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001413
1414 Logs a message with integer level *lvl* on this logger. The other arguments are
1415 interpreted as for :meth:`debug`.
1416
1417
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001418.. method:: Logger.exception(msg, *args)
Georg Brandl116aa622007-08-15 14:28:22 +00001419
1420 Logs a message with level :const:`ERROR` on this logger. The arguments are
1421 interpreted as for :meth:`debug`. Exception info is added to the logging
1422 message. This method should only be called from an exception handler.
1423
1424
1425.. method:: Logger.addFilter(filt)
1426
1427 Adds the specified filter *filt* to this logger.
1428
1429
1430.. method:: Logger.removeFilter(filt)
1431
1432 Removes the specified filter *filt* from this logger.
1433
1434
1435.. method:: Logger.filter(record)
1436
1437 Applies this logger's filters to the record and returns a true value if the
1438 record is to be processed.
1439
1440
1441.. method:: Logger.addHandler(hdlr)
1442
1443 Adds the specified handler *hdlr* to this logger.
1444
1445
1446.. method:: Logger.removeHandler(hdlr)
1447
1448 Removes the specified handler *hdlr* from this logger.
1449
1450
Vinay Sajip8593ae62010-11-14 21:33:04 +00001451.. method:: Logger.findCaller(stack_info=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001452
1453 Finds the caller's source filename and line number. Returns the filename, line
Vinay Sajip8593ae62010-11-14 21:33:04 +00001454 number, function name and stack information as a 4-element tuple. The stack
1455 information is returned as *None* unless *stack_info* is *True*.
Georg Brandl116aa622007-08-15 14:28:22 +00001456
Georg Brandl116aa622007-08-15 14:28:22 +00001457
1458.. method:: Logger.handle(record)
1459
1460 Handles a record by passing it to all handlers associated with this logger and
1461 its ancestors (until a false value of *propagate* is found). This method is used
1462 for unpickled records received from a socket, as well as those created locally.
Georg Brandl502d9a52009-07-26 15:02:41 +00001463 Logger-level filtering is applied using :meth:`~Logger.filter`.
Georg Brandl116aa622007-08-15 14:28:22 +00001464
1465
Vinay Sajip8593ae62010-11-14 21:33:04 +00001466.. method:: Logger.makeRecord(name, lvl, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001467
1468 This is a factory method which can be overridden in subclasses to create
1469 specialized :class:`LogRecord` instances.
1470
Vinay Sajip83eadd12010-09-20 10:31:18 +00001471.. method:: Logger.hasHandlers()
1472
1473 Checks to see if this logger has any handlers configured. This is done by
1474 looking for handlers in this logger and its parents in the logger hierarchy.
1475 Returns True if a handler was found, else False. The method stops searching
1476 up the hierarchy whenever a logger with the "propagate" attribute set to
1477 False is found - that will be the last logger which is checked for the
1478 existence of handlers.
1479
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001480 .. versionadded:: 3.2
Vinay Sajip83eadd12010-09-20 10:31:18 +00001481
Vinay Sajipa18b9592010-12-12 13:20:55 +00001482.. _basic-example:
Georg Brandl116aa622007-08-15 14:28:22 +00001483
1484Basic example
1485-------------
1486
Georg Brandl116aa622007-08-15 14:28:22 +00001487The :mod:`logging` package provides a lot of flexibility, and its configuration
1488can appear daunting. This section demonstrates that simple use of the logging
1489package is possible.
1490
1491The simplest example shows logging to the console::
1492
1493 import logging
1494
1495 logging.debug('A debug message')
1496 logging.info('Some information')
1497 logging.warning('A shot across the bows')
1498
1499If you run the above script, you'll see this::
1500
1501 WARNING:root:A shot across the bows
1502
1503Because no particular logger was specified, the system used the root logger. The
1504debug and info messages didn't appear because by default, the root logger is
1505configured to only handle messages with a severity of WARNING or above. The
1506message format is also a configuration default, as is the output destination of
1507the messages - ``sys.stderr``. The severity level, the message format and
1508destination can be easily changed, as shown in the example below::
1509
1510 import logging
1511
1512 logging.basicConfig(level=logging.DEBUG,
1513 format='%(asctime)s %(levelname)s %(message)s',
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001514 filename='myapp.log',
Georg Brandl116aa622007-08-15 14:28:22 +00001515 filemode='w')
1516 logging.debug('A debug message')
1517 logging.info('Some information')
1518 logging.warning('A shot across the bows')
1519
1520The :meth:`basicConfig` method is used to change the configuration defaults,
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001521which results in output (written to ``myapp.log``) which should look
Georg Brandl116aa622007-08-15 14:28:22 +00001522something like the following::
1523
1524 2004-07-02 13:00:08,743 DEBUG A debug message
1525 2004-07-02 13:00:08,743 INFO Some information
1526 2004-07-02 13:00:08,743 WARNING A shot across the bows
1527
1528This time, all messages with a severity of DEBUG or above were handled, and the
1529format of the messages was also changed, and output went to the specified file
1530rather than the console.
1531
Georg Brandl81ac1ce2007-08-31 17:17:17 +00001532.. XXX logging should probably be updated for new string formatting!
Georg Brandl4b491312007-08-31 09:22:56 +00001533
1534Formatting uses the old Python string formatting - see section
1535:ref:`old-string-formatting`. The format string takes the following common
Georg Brandl116aa622007-08-15 14:28:22 +00001536specifiers. For a complete list of specifiers, consult the :class:`Formatter`
1537documentation.
1538
1539+-------------------+-----------------------------------------------+
1540| Format | Description |
1541+===================+===============================================+
1542| ``%(name)s`` | Name of the logger (logging channel). |
1543+-------------------+-----------------------------------------------+
1544| ``%(levelname)s`` | Text logging level for the message |
1545| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
1546| | ``'ERROR'``, ``'CRITICAL'``). |
1547+-------------------+-----------------------------------------------+
1548| ``%(asctime)s`` | Human-readable time when the |
1549| | :class:`LogRecord` was created. By default |
1550| | this is of the form "2003-07-08 16:49:45,896" |
1551| | (the numbers after the comma are millisecond |
1552| | portion of the time). |
1553+-------------------+-----------------------------------------------+
1554| ``%(message)s`` | The logged message. |
1555+-------------------+-----------------------------------------------+
1556
1557To change the date/time format, you can pass an additional keyword parameter,
1558*datefmt*, as in the following::
1559
1560 import logging
1561
1562 logging.basicConfig(level=logging.DEBUG,
1563 format='%(asctime)s %(levelname)-8s %(message)s',
1564 datefmt='%a, %d %b %Y %H:%M:%S',
1565 filename='/temp/myapp.log',
1566 filemode='w')
1567 logging.debug('A debug message')
1568 logging.info('Some information')
1569 logging.warning('A shot across the bows')
1570
1571which would result in output like ::
1572
1573 Fri, 02 Jul 2004 13:06:18 DEBUG A debug message
1574 Fri, 02 Jul 2004 13:06:18 INFO Some information
1575 Fri, 02 Jul 2004 13:06:18 WARNING A shot across the bows
1576
1577The date format string follows the requirements of :func:`strftime` - see the
1578documentation for the :mod:`time` module.
1579
1580If, instead of sending logging output to the console or a file, you'd rather use
1581a file-like object which you have created separately, you can pass it to
1582:func:`basicConfig` using the *stream* keyword argument. Note that if both
1583*stream* and *filename* keyword arguments are passed, the *stream* argument is
1584ignored.
1585
1586Of course, you can put variable information in your output. To do this, simply
1587have the message be a format string and pass in additional arguments containing
1588the variable information, as in the following example::
1589
1590 import logging
1591
1592 logging.basicConfig(level=logging.DEBUG,
1593 format='%(asctime)s %(levelname)-8s %(message)s',
1594 datefmt='%a, %d %b %Y %H:%M:%S',
1595 filename='/temp/myapp.log',
1596 filemode='w')
1597 logging.error('Pack my box with %d dozen %s', 5, 'liquor jugs')
1598
1599which would result in ::
1600
1601 Wed, 21 Jul 2004 15:35:16 ERROR Pack my box with 5 dozen liquor jugs
1602
1603
Vinay Sajipa18b9592010-12-12 13:20:55 +00001604Using file rotation
1605^^^^^^^^^^^^^^^^^^^
1606
1607.. sectionauthor:: Doug Hellmann, Vinay Sajip (changes)
1608.. (see <http://blog.doughellmann.com/2007/05/pymotw-logging.html>)
1609
1610Sometimes you want to let a log file grow to a certain size, then open a new
1611file and log to that. You may want to keep a certain number of these files, and
1612when that many files have been created, rotate the files so that the number of
1613files and the size of the files both remin bounded. For this usage pattern, the
1614logging package provides a :class:`RotatingFileHandler`::
1615
1616 import glob
1617 import logging
1618 import logging.handlers
1619
1620 LOG_FILENAME = 'logging_rotatingfile_example.out'
1621
1622 # Set up a specific logger with our desired output level
1623 my_logger = logging.getLogger('MyLogger')
1624 my_logger.setLevel(logging.DEBUG)
1625
1626 # Add the log message handler to the logger
1627 handler = logging.handlers.RotatingFileHandler(
1628 LOG_FILENAME, maxBytes=20, backupCount=5)
1629
1630 my_logger.addHandler(handler)
1631
1632 # Log some messages
1633 for i in range(20):
1634 my_logger.debug('i = %d' % i)
1635
1636 # See what files are created
1637 logfiles = glob.glob('%s*' % LOG_FILENAME)
1638
1639 for filename in logfiles:
1640 print(filename)
1641
1642The result should be 6 separate files, each with part of the log history for the
1643application::
1644
1645 logging_rotatingfile_example.out
1646 logging_rotatingfile_example.out.1
1647 logging_rotatingfile_example.out.2
1648 logging_rotatingfile_example.out.3
1649 logging_rotatingfile_example.out.4
1650 logging_rotatingfile_example.out.5
1651
1652The most current file is always :file:`logging_rotatingfile_example.out`,
1653and each time it reaches the size limit it is renamed with the suffix
1654``.1``. Each of the existing backup files is renamed to increment the suffix
1655(``.1`` becomes ``.2``, etc.) and the ``.6`` file is erased.
1656
1657Obviously this example sets the log length much much too small as an extreme
1658example. You would want to set *maxBytes* to an appropriate value.
1659
1660
1661The logger, handler, and log message call each specify a level. The log message
1662is only emitted if the handler and logger are configured to emit messages of
1663that level or lower. For example, if a message is ``CRITICAL``, and the logger
1664is set to ``ERROR``, the message is emitted. If a message is a ``WARNING``, and
1665the logger is set to produce only ``ERROR``\s, the message is not emitted::
1666
1667 import logging
1668 import sys
1669
1670 LEVELS = {'debug': logging.DEBUG,
1671 'info': logging.INFO,
1672 'warning': logging.WARNING,
1673 'error': logging.ERROR,
1674 'critical': logging.CRITICAL}
1675
1676 if len(sys.argv) > 1:
1677 level_name = sys.argv[1]
1678 level = LEVELS.get(level_name, logging.NOTSET)
1679 logging.basicConfig(level=level)
1680
1681 logging.debug('This is a debug message')
1682 logging.info('This is an info message')
1683 logging.warning('This is a warning message')
1684 logging.error('This is an error message')
1685 logging.critical('This is a critical error message')
1686
1687Run the script with an argument like 'debug' or 'warning' to see which messages
1688show up at different levels::
1689
1690 $ python logging_level_example.py debug
1691 DEBUG:root:This is a debug message
1692 INFO:root:This is an info message
1693 WARNING:root:This is a warning message
1694 ERROR:root:This is an error message
1695 CRITICAL:root:This is a critical error message
1696
1697 $ python logging_level_example.py info
1698 INFO:root:This is an info message
1699 WARNING:root:This is a warning message
1700 ERROR:root:This is an error message
1701 CRITICAL:root:This is a critical error message
1702
1703You will notice that these log messages all have ``root`` embedded in them. The
1704logging module supports a hierarchy of loggers with different names. An easy
1705way to tell where a specific log message comes from is to use a separate logger
1706object for each of your modules. Each new logger "inherits" the configuration
1707of its parent, and log messages sent to a logger include the name of that
1708logger. Optionally, each logger can be configured differently, so that messages
1709from different modules are handled in different ways. Let's look at a simple
1710example of how to log from different modules so it is easy to trace the source
1711of the message::
1712
1713 import logging
1714
1715 logging.basicConfig(level=logging.WARNING)
1716
1717 logger1 = logging.getLogger('package1.module1')
1718 logger2 = logging.getLogger('package2.module2')
1719
1720 logger1.warning('This message comes from one module')
1721 logger2.warning('And this message comes from another module')
1722
1723And the output::
1724
1725 $ python logging_modules_example.py
1726 WARNING:package1.module1:This message comes from one module
1727 WARNING:package2.module2:And this message comes from another module
1728
1729There are many more options for configuring logging, including different log
1730message formatting options, having messages delivered to multiple destinations,
1731and changing the configuration of a long-running application on the fly using a
1732socket interface. All of these options are covered in depth in the library
1733module documentation.
1734
1735
Georg Brandl116aa622007-08-15 14:28:22 +00001736.. _multiple-destinations:
1737
1738Logging to multiple destinations
1739--------------------------------
1740
1741Let's say you want to log to console and file with different message formats and
1742in differing circumstances. Say you want to log messages with levels of DEBUG
1743and higher to file, and those messages at level INFO and higher to the console.
1744Let's also assume that the file should contain timestamps, but the console
1745messages should not. Here's how you can achieve this::
1746
1747 import logging
1748
1749 # set up logging to file - see previous section for more details
1750 logging.basicConfig(level=logging.DEBUG,
1751 format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
1752 datefmt='%m-%d %H:%M',
1753 filename='/temp/myapp.log',
1754 filemode='w')
1755 # define a Handler which writes INFO messages or higher to the sys.stderr
1756 console = logging.StreamHandler()
1757 console.setLevel(logging.INFO)
1758 # set a format which is simpler for console use
1759 formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
1760 # tell the handler to use this format
1761 console.setFormatter(formatter)
1762 # add the handler to the root logger
1763 logging.getLogger('').addHandler(console)
1764
1765 # Now, we can log to the root logger, or any other logger. First the root...
1766 logging.info('Jackdaws love my big sphinx of quartz.')
1767
1768 # Now, define a couple of other loggers which might represent areas in your
1769 # application:
1770
1771 logger1 = logging.getLogger('myapp.area1')
1772 logger2 = logging.getLogger('myapp.area2')
1773
1774 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
1775 logger1.info('How quickly daft jumping zebras vex.')
1776 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
1777 logger2.error('The five boxing wizards jump quickly.')
1778
1779When you run this, on the console you will see ::
1780
1781 root : INFO Jackdaws love my big sphinx of quartz.
1782 myapp.area1 : INFO How quickly daft jumping zebras vex.
1783 myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.
1784 myapp.area2 : ERROR The five boxing wizards jump quickly.
1785
1786and in the file you will see something like ::
1787
1788 10-22 22:19 root INFO Jackdaws love my big sphinx of quartz.
1789 10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
1790 10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.
1791 10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
1792 10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.
1793
1794As you can see, the DEBUG message only shows up in the file. The other messages
1795are sent to both destinations.
1796
1797This example uses console and file handlers, but you can use any number and
1798combination of handlers you choose.
1799
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001800.. _logging-exceptions:
1801
1802Exceptions raised during logging
1803--------------------------------
1804
1805The logging package is designed to swallow exceptions which occur while logging
1806in production. This is so that errors which occur while handling logging events
1807- such as logging misconfiguration, network or other similar errors - do not
1808cause the application using logging to terminate prematurely.
1809
1810:class:`SystemExit` and :class:`KeyboardInterrupt` exceptions are never
1811swallowed. Other exceptions which occur during the :meth:`emit` method of a
1812:class:`Handler` subclass are passed to its :meth:`handleError` method.
1813
1814The default implementation of :meth:`handleError` in :class:`Handler` checks
Georg Brandlef871f62010-03-12 10:06:40 +00001815to see if a module-level variable, :data:`raiseExceptions`, is set. If set, a
1816traceback is printed to :data:`sys.stderr`. If not set, the exception is swallowed.
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001817
Georg Brandlef871f62010-03-12 10:06:40 +00001818**Note:** The default value of :data:`raiseExceptions` is ``True``. This is because
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001819during development, you typically want to be notified of any exceptions that
Georg Brandlef871f62010-03-12 10:06:40 +00001820occur. It's advised that you set :data:`raiseExceptions` to ``False`` for production
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001821usage.
Georg Brandl116aa622007-08-15 14:28:22 +00001822
Christian Heimes790c8232008-01-07 21:14:23 +00001823.. _context-info:
1824
1825Adding contextual information to your logging output
1826----------------------------------------------------
1827
1828Sometimes you want logging output to contain contextual information in
1829addition to the parameters passed to the logging call. For example, in a
1830networked application, it may be desirable to log client-specific information
1831in the log (e.g. remote client's username, or IP address). Although you could
1832use the *extra* parameter to achieve this, it's not always convenient to pass
1833the information in this way. While it might be tempting to create
1834:class:`Logger` instances on a per-connection basis, this is not a good idea
1835because these instances are not garbage collected. While this is not a problem
1836in practice, when the number of :class:`Logger` instances is dependent on the
1837level of granularity you want to use in logging an application, it could
1838be hard to manage if the number of :class:`Logger` instances becomes
1839effectively unbounded.
1840
Vinay Sajipc31be632010-09-06 22:18:20 +00001841
1842Using LoggerAdapters to impart contextual information
1843^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1844
Christian Heimes04c420f2008-01-18 18:40:46 +00001845An easy way in which you can pass contextual information to be output along
1846with logging event information is to use the :class:`LoggerAdapter` class.
1847This class is designed to look like a :class:`Logger`, so that you can call
1848:meth:`debug`, :meth:`info`, :meth:`warning`, :meth:`error`,
1849:meth:`exception`, :meth:`critical` and :meth:`log`. These methods have the
1850same signatures as their counterparts in :class:`Logger`, so you can use the
1851two types of instances interchangeably.
Christian Heimes790c8232008-01-07 21:14:23 +00001852
Christian Heimes04c420f2008-01-18 18:40:46 +00001853When you create an instance of :class:`LoggerAdapter`, you pass it a
1854:class:`Logger` instance and a dict-like object which contains your contextual
1855information. When you call one of the logging methods on an instance of
1856:class:`LoggerAdapter`, it delegates the call to the underlying instance of
1857:class:`Logger` passed to its constructor, and arranges to pass the contextual
1858information in the delegated call. Here's a snippet from the code of
1859:class:`LoggerAdapter`::
Christian Heimes790c8232008-01-07 21:14:23 +00001860
Christian Heimes04c420f2008-01-18 18:40:46 +00001861 def debug(self, msg, *args, **kwargs):
1862 """
1863 Delegate a debug call to the underlying logger, after adding
1864 contextual information from this adapter instance.
1865 """
1866 msg, kwargs = self.process(msg, kwargs)
1867 self.logger.debug(msg, *args, **kwargs)
Christian Heimes790c8232008-01-07 21:14:23 +00001868
Christian Heimes04c420f2008-01-18 18:40:46 +00001869The :meth:`process` method of :class:`LoggerAdapter` is where the contextual
1870information is added to the logging output. It's passed the message and
1871keyword arguments of the logging call, and it passes back (potentially)
1872modified versions of these to use in the call to the underlying logger. The
1873default implementation of this method leaves the message alone, but inserts
1874an "extra" key in the keyword argument whose value is the dict-like object
1875passed to the constructor. Of course, if you had passed an "extra" keyword
1876argument in the call to the adapter, it will be silently overwritten.
Christian Heimes790c8232008-01-07 21:14:23 +00001877
Christian Heimes04c420f2008-01-18 18:40:46 +00001878The advantage of using "extra" is that the values in the dict-like object are
1879merged into the :class:`LogRecord` instance's __dict__, allowing you to use
1880customized strings with your :class:`Formatter` instances which know about
1881the keys of the dict-like object. If you need a different method, e.g. if you
1882want to prepend or append the contextual information to the message string,
1883you just need to subclass :class:`LoggerAdapter` and override :meth:`process`
1884to do what you need. Here's an example script which uses this class, which
1885also illustrates what dict-like behaviour is needed from an arbitrary
1886"dict-like" object for use in the constructor::
1887
Christian Heimes587c2bf2008-01-19 16:21:02 +00001888 import logging
Georg Brandl86def6c2008-01-21 20:36:10 +00001889
Christian Heimes587c2bf2008-01-19 16:21:02 +00001890 class ConnInfo:
1891 """
1892 An example class which shows how an arbitrary class can be used as
1893 the 'extra' context information repository passed to a LoggerAdapter.
1894 """
Georg Brandl86def6c2008-01-21 20:36:10 +00001895
Christian Heimes587c2bf2008-01-19 16:21:02 +00001896 def __getitem__(self, name):
1897 """
1898 To allow this instance to look like a dict.
1899 """
1900 from random import choice
1901 if name == "ip":
1902 result = choice(["127.0.0.1", "192.168.0.1"])
1903 elif name == "user":
1904 result = choice(["jim", "fred", "sheila"])
1905 else:
1906 result = self.__dict__.get(name, "?")
1907 return result
Georg Brandl86def6c2008-01-21 20:36:10 +00001908
Christian Heimes587c2bf2008-01-19 16:21:02 +00001909 def __iter__(self):
1910 """
1911 To allow iteration over keys, which will be merged into
1912 the LogRecord dict before formatting and output.
1913 """
1914 keys = ["ip", "user"]
1915 keys.extend(self.__dict__.keys())
1916 return keys.__iter__()
Georg Brandl86def6c2008-01-21 20:36:10 +00001917
Christian Heimes587c2bf2008-01-19 16:21:02 +00001918 if __name__ == "__main__":
1919 from random import choice
1920 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
1921 a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"),
1922 { "ip" : "123.231.231.123", "user" : "sheila" })
1923 logging.basicConfig(level=logging.DEBUG,
1924 format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s")
1925 a1.debug("A debug message")
1926 a1.info("An info message with %s", "some parameters")
1927 a2 = logging.LoggerAdapter(logging.getLogger("d.e.f"), ConnInfo())
1928 for x in range(10):
1929 lvl = choice(levels)
1930 lvlname = logging.getLevelName(lvl)
1931 a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters")
Christian Heimes04c420f2008-01-18 18:40:46 +00001932
1933When this script is run, the output should look something like this::
1934
Christian Heimes587c2bf2008-01-19 16:21:02 +00001935 2008-01-18 14:49:54,023 a.b.c DEBUG IP: 123.231.231.123 User: sheila A debug message
1936 2008-01-18 14:49:54,023 a.b.c INFO IP: 123.231.231.123 User: sheila An info message with some parameters
1937 2008-01-18 14:49:54,023 d.e.f CRITICAL IP: 192.168.0.1 User: jim A message at CRITICAL level with 2 parameters
1938 2008-01-18 14:49:54,033 d.e.f INFO IP: 192.168.0.1 User: jim A message at INFO level with 2 parameters
1939 2008-01-18 14:49:54,033 d.e.f WARNING IP: 192.168.0.1 User: sheila A message at WARNING level with 2 parameters
1940 2008-01-18 14:49:54,033 d.e.f ERROR IP: 127.0.0.1 User: fred A message at ERROR level with 2 parameters
1941 2008-01-18 14:49:54,033 d.e.f ERROR IP: 127.0.0.1 User: sheila A message at ERROR level with 2 parameters
1942 2008-01-18 14:49:54,033 d.e.f WARNING IP: 192.168.0.1 User: sheila A message at WARNING level with 2 parameters
1943 2008-01-18 14:49:54,033 d.e.f WARNING IP: 192.168.0.1 User: jim A message at WARNING level with 2 parameters
1944 2008-01-18 14:49:54,033 d.e.f INFO IP: 192.168.0.1 User: fred A message at INFO level with 2 parameters
1945 2008-01-18 14:49:54,033 d.e.f WARNING IP: 192.168.0.1 User: sheila A message at WARNING level with 2 parameters
1946 2008-01-18 14:49:54,033 d.e.f WARNING IP: 127.0.0.1 User: jim A message at WARNING level with 2 parameters
Christian Heimes04c420f2008-01-18 18:40:46 +00001947
Christian Heimes790c8232008-01-07 21:14:23 +00001948
Vinay Sajipac007992010-09-17 12:45:26 +00001949.. _filters-contextual:
1950
Vinay Sajipc31be632010-09-06 22:18:20 +00001951Using Filters to impart contextual information
1952^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1953
1954You can also add contextual information to log output using a user-defined
1955:class:`Filter`. ``Filter`` instances are allowed to modify the ``LogRecords``
1956passed to them, including adding additional attributes which can then be output
1957using a suitable format string, or if needed a custom :class:`Formatter`.
1958
1959For example in a web application, the request being processed (or at least,
1960the interesting parts of it) can be stored in a threadlocal
1961(:class:`threading.local`) variable, and then accessed from a ``Filter`` to
1962add, say, information from the request - say, the remote IP address and remote
1963user's username - to the ``LogRecord``, using the attribute names 'ip' and
1964'user' as in the ``LoggerAdapter`` example above. In that case, the same format
1965string can be used to get similar output to that shown above. Here's an example
1966script::
1967
1968 import logging
1969 from random import choice
1970
1971 class ContextFilter(logging.Filter):
1972 """
1973 This is a filter which injects contextual information into the log.
1974
1975 Rather than use actual contextual information, we just use random
1976 data in this demo.
1977 """
1978
1979 USERS = ['jim', 'fred', 'sheila']
1980 IPS = ['123.231.231.123', '127.0.0.1', '192.168.0.1']
1981
1982 def filter(self, record):
1983
1984 record.ip = choice(ContextFilter.IPS)
1985 record.user = choice(ContextFilter.USERS)
1986 return True
1987
1988 if __name__ == "__main__":
1989 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
1990 a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"),
1991 { "ip" : "123.231.231.123", "user" : "sheila" })
1992 logging.basicConfig(level=logging.DEBUG,
1993 format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s")
1994 a1 = logging.getLogger("a.b.c")
1995 a2 = logging.getLogger("d.e.f")
1996
1997 f = ContextFilter()
1998 a1.addFilter(f)
1999 a2.addFilter(f)
2000 a1.debug("A debug message")
2001 a1.info("An info message with %s", "some parameters")
2002 for x in range(10):
2003 lvl = choice(levels)
2004 lvlname = logging.getLevelName(lvl)
2005 a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters")
2006
2007which, when run, produces something like::
2008
2009 2010-09-06 22:38:15,292 a.b.c DEBUG IP: 123.231.231.123 User: fred A debug message
2010 2010-09-06 22:38:15,300 a.b.c INFO IP: 192.168.0.1 User: sheila An info message with some parameters
2011 2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1 User: sheila A message at CRITICAL level with 2 parameters
2012 2010-09-06 22:38:15,300 d.e.f ERROR IP: 127.0.0.1 User: jim A message at ERROR level with 2 parameters
2013 2010-09-06 22:38:15,300 d.e.f DEBUG IP: 127.0.0.1 User: sheila A message at DEBUG level with 2 parameters
2014 2010-09-06 22:38:15,300 d.e.f ERROR IP: 123.231.231.123 User: fred A message at ERROR level with 2 parameters
2015 2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 192.168.0.1 User: jim A message at CRITICAL level with 2 parameters
2016 2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1 User: sheila A message at CRITICAL level with 2 parameters
2017 2010-09-06 22:38:15,300 d.e.f DEBUG IP: 192.168.0.1 User: jim A message at DEBUG level with 2 parameters
2018 2010-09-06 22:38:15,301 d.e.f ERROR IP: 127.0.0.1 User: sheila A message at ERROR level with 2 parameters
2019 2010-09-06 22:38:15,301 d.e.f DEBUG IP: 123.231.231.123 User: fred A message at DEBUG level with 2 parameters
2020 2010-09-06 22:38:15,301 d.e.f INFO IP: 123.231.231.123 User: fred A message at INFO level with 2 parameters
2021
2022
Vinay Sajipd31f3632010-06-29 15:31:15 +00002023.. _multiple-processes:
2024
Vinay Sajipa7471bf2009-08-15 23:23:37 +00002025Logging to a single file from multiple processes
2026------------------------------------------------
2027
2028Although logging is thread-safe, and logging to a single file from multiple
2029threads in a single process *is* supported, logging to a single file from
2030*multiple processes* is *not* supported, because there is no standard way to
2031serialize access to a single file across multiple processes in Python. If you
Vinay Sajip121a1c42010-09-08 10:46:15 +00002032need to log to a single file from multiple processes, one way of doing this is
2033to have all the processes log to a :class:`SocketHandler`, and have a separate
2034process which implements a socket server which reads from the socket and logs
2035to file. (If you prefer, you can dedicate one thread in one of the existing
2036processes to perform this function.) The following section documents this
2037approach in more detail and includes a working socket receiver which can be
2038used as a starting point for you to adapt in your own applications.
Vinay Sajipa7471bf2009-08-15 23:23:37 +00002039
Vinay Sajip5a92b132009-08-15 23:35:08 +00002040If you are using a recent version of Python which includes the
Vinay Sajip121a1c42010-09-08 10:46:15 +00002041:mod:`multiprocessing` module, you could write your own handler which uses the
Vinay Sajip5a92b132009-08-15 23:35:08 +00002042:class:`Lock` class from this module to serialize access to the file from
2043your processes. The existing :class:`FileHandler` and subclasses do not make
2044use of :mod:`multiprocessing` at present, though they may do so in the future.
Vinay Sajip8c6b0a52009-08-17 13:17:47 +00002045Note that at present, the :mod:`multiprocessing` module does not provide
2046working lock functionality on all platforms (see
2047http://bugs.python.org/issue3770).
Vinay Sajip5a92b132009-08-15 23:35:08 +00002048
Vinay Sajip121a1c42010-09-08 10:46:15 +00002049.. currentmodule:: logging.handlers
2050
2051Alternatively, you can use a ``Queue`` and a :class:`QueueHandler` to send
2052all logging events to one of the processes in your multi-process application.
2053The following example script demonstrates how you can do this; in the example
2054a separate listener process listens for events sent by other processes and logs
2055them according to its own logging configuration. Although the example only
2056demonstrates one way of doing it (for example, you may want to use a listener
2057thread rather than a separate listener process - the implementation would be
2058analogous) it does allow for completely different logging configurations for
2059the listener and the other processes in your application, and can be used as
2060the basis for code meeting your own specific requirements::
2061
2062 # You'll need these imports in your own code
2063 import logging
2064 import logging.handlers
2065 import multiprocessing
2066
2067 # Next two import lines for this demo only
2068 from random import choice, random
2069 import time
2070
2071 #
2072 # Because you'll want to define the logging configurations for listener and workers, the
2073 # listener and worker process functions take a configurer parameter which is a callable
2074 # for configuring logging for that process. These functions are also passed the queue,
2075 # which they use for communication.
2076 #
2077 # In practice, you can configure the listener however you want, but note that in this
2078 # simple example, the listener does not apply level or filter logic to received records.
2079 # In practice, you would probably want to do ths logic in the worker processes, to avoid
2080 # sending events which would be filtered out between processes.
2081 #
2082 # The size of the rotated files is made small so you can see the results easily.
2083 def listener_configurer():
2084 root = logging.getLogger()
2085 h = logging.handlers.RotatingFileHandler('/tmp/mptest.log', 'a', 300, 10)
2086 f = logging.Formatter('%(asctime)s %(processName)-10s %(name)s %(levelname)-8s %(message)s')
2087 h.setFormatter(f)
2088 root.addHandler(h)
2089
2090 # This is the listener process top-level loop: wait for logging events
2091 # (LogRecords)on the queue and handle them, quit when you get a None for a
2092 # LogRecord.
2093 def listener_process(queue, configurer):
2094 configurer()
2095 while True:
2096 try:
2097 record = queue.get()
2098 if record is None: # We send this as a sentinel to tell the listener to quit.
2099 break
2100 logger = logging.getLogger(record.name)
2101 logger.handle(record) # No level or filter logic applied - just do it!
2102 except (KeyboardInterrupt, SystemExit):
2103 raise
2104 except:
2105 import sys, traceback
2106 print >> sys.stderr, 'Whoops! Problem:'
2107 traceback.print_exc(file=sys.stderr)
2108
2109 # Arrays used for random selections in this demo
2110
2111 LEVELS = [logging.DEBUG, logging.INFO, logging.WARNING,
2112 logging.ERROR, logging.CRITICAL]
2113
2114 LOGGERS = ['a.b.c', 'd.e.f']
2115
2116 MESSAGES = [
2117 'Random message #1',
2118 'Random message #2',
2119 'Random message #3',
2120 ]
2121
2122 # The worker configuration is done at the start of the worker process run.
2123 # Note that on Windows you can't rely on fork semantics, so each process
2124 # will run the logging configuration code when it starts.
2125 def worker_configurer(queue):
2126 h = logging.handlers.QueueHandler(queue) # Just the one handler needed
2127 root = logging.getLogger()
2128 root.addHandler(h)
2129 root.setLevel(logging.DEBUG) # send all messages, for demo; no other level or filter logic applied.
2130
2131 # This is the worker process top-level loop, which just logs ten events with
2132 # random intervening delays before terminating.
2133 # The print messages are just so you know it's doing something!
2134 def worker_process(queue, configurer):
2135 configurer(queue)
2136 name = multiprocessing.current_process().name
2137 print('Worker started: %s' % name)
2138 for i in range(10):
2139 time.sleep(random())
2140 logger = logging.getLogger(choice(LOGGERS))
2141 level = choice(LEVELS)
2142 message = choice(MESSAGES)
2143 logger.log(level, message)
2144 print('Worker finished: %s' % name)
2145
2146 # Here's where the demo gets orchestrated. Create the queue, create and start
2147 # the listener, create ten workers and start them, wait for them to finish,
2148 # then send a None to the queue to tell the listener to finish.
2149 def main():
2150 queue = multiprocessing.Queue(-1)
2151 listener = multiprocessing.Process(target=listener_process,
2152 args=(queue, listener_configurer))
2153 listener.start()
2154 workers = []
2155 for i in range(10):
2156 worker = multiprocessing.Process(target=worker_process,
2157 args=(queue, worker_configurer))
2158 workers.append(worker)
2159 worker.start()
2160 for w in workers:
2161 w.join()
2162 queue.put_nowait(None)
2163 listener.join()
2164
2165 if __name__ == '__main__':
2166 main()
2167
2168
2169.. currentmodule:: logging
2170
Benjamin Peterson8719ad52009-09-11 22:24:02 +00002171
Georg Brandl116aa622007-08-15 14:28:22 +00002172.. _network-logging:
2173
2174Sending and receiving logging events across a network
2175-----------------------------------------------------
2176
2177Let's say you want to send logging events across a network, and handle them at
2178the receiving end. A simple way of doing this is attaching a
2179:class:`SocketHandler` instance to the root logger at the sending end::
2180
2181 import logging, logging.handlers
2182
2183 rootLogger = logging.getLogger('')
2184 rootLogger.setLevel(logging.DEBUG)
2185 socketHandler = logging.handlers.SocketHandler('localhost',
2186 logging.handlers.DEFAULT_TCP_LOGGING_PORT)
2187 # don't bother with a formatter, since a socket handler sends the event as
2188 # an unformatted pickle
2189 rootLogger.addHandler(socketHandler)
2190
2191 # Now, we can log to the root logger, or any other logger. First the root...
2192 logging.info('Jackdaws love my big sphinx of quartz.')
2193
2194 # Now, define a couple of other loggers which might represent areas in your
2195 # application:
2196
2197 logger1 = logging.getLogger('myapp.area1')
2198 logger2 = logging.getLogger('myapp.area2')
2199
2200 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
2201 logger1.info('How quickly daft jumping zebras vex.')
2202 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
2203 logger2.error('The five boxing wizards jump quickly.')
2204
Alexandre Vassalottice261952008-05-12 02:31:37 +00002205At the receiving end, you can set up a receiver using the :mod:`socketserver`
Georg Brandl116aa622007-08-15 14:28:22 +00002206module. Here is a basic working example::
2207
Georg Brandla35f4b92009-05-31 16:41:59 +00002208 import pickle
Georg Brandl116aa622007-08-15 14:28:22 +00002209 import logging
2210 import logging.handlers
Alexandre Vassalottice261952008-05-12 02:31:37 +00002211 import socketserver
Georg Brandl116aa622007-08-15 14:28:22 +00002212 import struct
2213
2214
Alexandre Vassalottice261952008-05-12 02:31:37 +00002215 class LogRecordStreamHandler(socketserver.StreamRequestHandler):
Georg Brandl116aa622007-08-15 14:28:22 +00002216 """Handler for a streaming logging request.
2217
2218 This basically logs the record using whatever logging policy is
2219 configured locally.
2220 """
2221
2222 def handle(self):
2223 """
2224 Handle multiple requests - each expected to be a 4-byte length,
2225 followed by the LogRecord in pickle format. Logs the record
2226 according to whatever policy is configured locally.
2227 """
Collin Winter46334482007-09-10 00:49:57 +00002228 while True:
Georg Brandl116aa622007-08-15 14:28:22 +00002229 chunk = self.connection.recv(4)
2230 if len(chunk) < 4:
2231 break
2232 slen = struct.unpack(">L", chunk)[0]
2233 chunk = self.connection.recv(slen)
2234 while len(chunk) < slen:
2235 chunk = chunk + self.connection.recv(slen - len(chunk))
2236 obj = self.unPickle(chunk)
2237 record = logging.makeLogRecord(obj)
2238 self.handleLogRecord(record)
2239
2240 def unPickle(self, data):
Georg Brandla35f4b92009-05-31 16:41:59 +00002241 return pickle.loads(data)
Georg Brandl116aa622007-08-15 14:28:22 +00002242
2243 def handleLogRecord(self, record):
2244 # if a name is specified, we use the named logger rather than the one
2245 # implied by the record.
2246 if self.server.logname is not None:
2247 name = self.server.logname
2248 else:
2249 name = record.name
2250 logger = logging.getLogger(name)
2251 # N.B. EVERY record gets logged. This is because Logger.handle
2252 # is normally called AFTER logger-level filtering. If you want
2253 # to do filtering, do it at the client end to save wasting
2254 # cycles and network bandwidth!
2255 logger.handle(record)
2256
Alexandre Vassalottice261952008-05-12 02:31:37 +00002257 class LogRecordSocketReceiver(socketserver.ThreadingTCPServer):
Georg Brandl116aa622007-08-15 14:28:22 +00002258 """simple TCP socket-based logging receiver suitable for testing.
2259 """
2260
2261 allow_reuse_address = 1
2262
2263 def __init__(self, host='localhost',
2264 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
2265 handler=LogRecordStreamHandler):
Alexandre Vassalottice261952008-05-12 02:31:37 +00002266 socketserver.ThreadingTCPServer.__init__(self, (host, port), handler)
Georg Brandl116aa622007-08-15 14:28:22 +00002267 self.abort = 0
2268 self.timeout = 1
2269 self.logname = None
2270
2271 def serve_until_stopped(self):
2272 import select
2273 abort = 0
2274 while not abort:
2275 rd, wr, ex = select.select([self.socket.fileno()],
2276 [], [],
2277 self.timeout)
2278 if rd:
2279 self.handle_request()
2280 abort = self.abort
2281
2282 def main():
2283 logging.basicConfig(
2284 format="%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s")
2285 tcpserver = LogRecordSocketReceiver()
Georg Brandl6911e3c2007-09-04 07:15:32 +00002286 print("About to start TCP server...")
Georg Brandl116aa622007-08-15 14:28:22 +00002287 tcpserver.serve_until_stopped()
2288
2289 if __name__ == "__main__":
2290 main()
2291
2292First run the server, and then the client. On the client side, nothing is
2293printed on the console; on the server side, you should see something like::
2294
2295 About to start TCP server...
2296 59 root INFO Jackdaws love my big sphinx of quartz.
2297 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
2298 69 myapp.area1 INFO How quickly daft jumping zebras vex.
2299 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
2300 69 myapp.area2 ERROR The five boxing wizards jump quickly.
2301
Vinay Sajipc15dfd62010-07-06 15:08:55 +00002302Note that there are some security issues with pickle in some scenarios. If
2303these affect you, you can use an alternative serialization scheme by overriding
2304the :meth:`makePickle` method and implementing your alternative there, as
2305well as adapting the above script to use your alternative serialization.
2306
Vinay Sajip4039aff2010-09-11 10:25:28 +00002307.. _arbitrary-object-messages:
2308
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002309Using arbitrary objects as messages
2310-----------------------------------
2311
2312In the preceding sections and examples, it has been assumed that the message
2313passed when logging the event is a string. However, this is not the only
2314possibility. You can pass an arbitrary object as a message, and its
2315:meth:`__str__` method will be called when the logging system needs to convert
2316it to a string representation. In fact, if you want to, you can avoid
2317computing a string representation altogether - for example, the
2318:class:`SocketHandler` emits an event by pickling it and sending it over the
2319wire.
2320
Vinay Sajip55778922010-09-23 09:09:15 +00002321Dealing with handlers that block
2322--------------------------------
2323
2324.. currentmodule:: logging.handlers
2325
2326Sometimes you have to get your logging handlers to do their work without
2327blocking the thread you’re logging from. This is common in Web applications,
2328though of course it also occurs in other scenarios.
2329
2330A common culprit which demonstrates sluggish behaviour is the
2331:class:`SMTPHandler`: sending emails can take a long time, for a
2332number of reasons outside the developer’s control (for example, a poorly
2333performing mail or network infrastructure). But almost any network-based
2334handler can block: Even a :class:`SocketHandler` operation may do a
2335DNS query under the hood which is too slow (and this query can be deep in the
2336socket library code, below the Python layer, and outside your control).
2337
2338One solution is to use a two-part approach. For the first part, attach only a
2339:class:`QueueHandler` to those loggers which are accessed from
2340performance-critical threads. They simply write to their queue, which can be
2341sized to a large enough capacity or initialized with no upper bound to their
2342size. The write to the queue will typically be accepted quickly, though you
2343will probably need to catch the :ref:`queue.Full` exception as a precaution
2344in your code. If you are a library developer who has performance-critical
2345threads in their code, be sure to document this (together with a suggestion to
2346attach only ``QueueHandlers`` to your loggers) for the benefit of other
2347developers who will use your code.
2348
2349The second part of the solution is :class:`QueueListener`, which has been
2350designed as the counterpart to :class:`QueueHandler`. A
2351:class:`QueueListener` is very simple: it’s passed a queue and some handlers,
2352and it fires up an internal thread which listens to its queue for LogRecords
2353sent from ``QueueHandlers`` (or any other source of ``LogRecords``, for that
2354matter). The ``LogRecords`` are removed from the queue and passed to the
2355handlers for processing.
2356
2357The advantage of having a separate :class:`QueueListener` class is that you
2358can use the same instance to service multiple ``QueueHandlers``. This is more
2359resource-friendly than, say, having threaded versions of the existing handler
2360classes, which would eat up one thread per handler for no particular benefit.
2361
2362An example of using these two classes follows (imports omitted)::
2363
2364 que = queue.Queue(-1) # no limit on size
2365 queue_handler = QueueHandler(que)
2366 handler = logging.StreamHandler()
2367 listener = QueueListener(que, handler)
2368 root = logging.getLogger()
2369 root.addHandler(queue_handler)
2370 formatter = logging.Formatter('%(threadName)s: %(message)s')
2371 handler.setFormatter(formatter)
2372 listener.start()
2373 # The log output will display the thread which generated
2374 # the event (the main thread) rather than the internal
2375 # thread which monitors the internal queue. This is what
2376 # you want to happen.
2377 root.warning('Look out!')
2378 listener.stop()
2379
2380which, when run, will produce::
2381
2382 MainThread: Look out!
2383
2384
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002385Optimization
2386------------
2387
2388Formatting of message arguments is deferred until it cannot be avoided.
2389However, computing the arguments passed to the logging method can also be
2390expensive, and you may want to avoid doing it if the logger will just throw
2391away your event. To decide what to do, you can call the :meth:`isEnabledFor`
2392method which takes a level argument and returns true if the event would be
2393created by the Logger for that level of call. You can write code like this::
2394
2395 if logger.isEnabledFor(logging.DEBUG):
2396 logger.debug("Message with %s, %s", expensive_func1(),
2397 expensive_func2())
2398
2399so that if the logger's threshold is set above ``DEBUG``, the calls to
2400:func:`expensive_func1` and :func:`expensive_func2` are never made.
2401
2402There are other optimizations which can be made for specific applications which
2403need more precise control over what logging information is collected. Here's a
2404list of things you can do to avoid processing during logging which you don't
2405need:
2406
2407+-----------------------------------------------+----------------------------------------+
2408| What you don't want to collect | How to avoid collecting it |
2409+===============================================+========================================+
2410| Information about where calls were made from. | Set ``logging._srcfile`` to ``None``. |
2411+-----------------------------------------------+----------------------------------------+
2412| Threading information. | Set ``logging.logThreads`` to ``0``. |
2413+-----------------------------------------------+----------------------------------------+
2414| Process information. | Set ``logging.logProcesses`` to ``0``. |
2415+-----------------------------------------------+----------------------------------------+
2416
2417Also note that the core logging module only includes the basic handlers. If
2418you don't import :mod:`logging.handlers` and :mod:`logging.config`, they won't
2419take up any memory.
2420
2421.. _handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002422
2423Handler Objects
2424---------------
2425
2426Handlers have the following attributes and methods. Note that :class:`Handler`
2427is never instantiated directly; this class acts as a base for more useful
2428subclasses. However, the :meth:`__init__` method in subclasses needs to call
2429:meth:`Handler.__init__`.
2430
2431
2432.. method:: Handler.__init__(level=NOTSET)
2433
2434 Initializes the :class:`Handler` instance by setting its level, setting the list
2435 of filters to the empty list and creating a lock (using :meth:`createLock`) for
2436 serializing access to an I/O mechanism.
2437
2438
2439.. method:: Handler.createLock()
2440
2441 Initializes a thread lock which can be used to serialize access to underlying
2442 I/O functionality which may not be threadsafe.
2443
2444
2445.. method:: Handler.acquire()
2446
2447 Acquires the thread lock created with :meth:`createLock`.
2448
2449
2450.. method:: Handler.release()
2451
2452 Releases the thread lock acquired with :meth:`acquire`.
2453
2454
2455.. method:: Handler.setLevel(lvl)
2456
2457 Sets the threshold for this handler to *lvl*. Logging messages which are less
2458 severe than *lvl* will be ignored. When a handler is created, the level is set
2459 to :const:`NOTSET` (which causes all messages to be processed).
2460
2461
2462.. method:: Handler.setFormatter(form)
2463
2464 Sets the :class:`Formatter` for this handler to *form*.
2465
2466
2467.. method:: Handler.addFilter(filt)
2468
2469 Adds the specified filter *filt* to this handler.
2470
2471
2472.. method:: Handler.removeFilter(filt)
2473
2474 Removes the specified filter *filt* from this handler.
2475
2476
2477.. method:: Handler.filter(record)
2478
2479 Applies this handler's filters to the record and returns a true value if the
2480 record is to be processed.
2481
2482
2483.. method:: Handler.flush()
2484
2485 Ensure all logging output has been flushed. This version does nothing and is
2486 intended to be implemented by subclasses.
2487
2488
2489.. method:: Handler.close()
2490
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002491 Tidy up any resources used by the handler. This version does no output but
2492 removes the handler from an internal list of handlers which is closed when
2493 :func:`shutdown` is called. Subclasses should ensure that this gets called
2494 from overridden :meth:`close` methods.
Georg Brandl116aa622007-08-15 14:28:22 +00002495
2496
2497.. method:: Handler.handle(record)
2498
2499 Conditionally emits the specified logging record, depending on filters which may
2500 have been added to the handler. Wraps the actual emission of the record with
2501 acquisition/release of the I/O thread lock.
2502
2503
2504.. method:: Handler.handleError(record)
2505
2506 This method should be called from handlers when an exception is encountered
2507 during an :meth:`emit` call. By default it does nothing, which means that
2508 exceptions get silently ignored. This is what is mostly wanted for a logging
2509 system - most users will not care about errors in the logging system, they are
2510 more interested in application errors. You could, however, replace this with a
2511 custom handler if you wish. The specified record is the one which was being
2512 processed when the exception occurred.
2513
2514
2515.. method:: Handler.format(record)
2516
2517 Do formatting for a record - if a formatter is set, use it. Otherwise, use the
2518 default formatter for the module.
2519
2520
2521.. method:: Handler.emit(record)
2522
2523 Do whatever it takes to actually log the specified logging record. This version
2524 is intended to be implemented by subclasses and so raises a
2525 :exc:`NotImplementedError`.
2526
2527
Vinay Sajipd31f3632010-06-29 15:31:15 +00002528.. _stream-handler:
2529
Georg Brandl116aa622007-08-15 14:28:22 +00002530StreamHandler
2531^^^^^^^^^^^^^
2532
2533The :class:`StreamHandler` class, located in the core :mod:`logging` package,
2534sends logging output to streams such as *sys.stdout*, *sys.stderr* or any
2535file-like object (or, more precisely, any object which supports :meth:`write`
2536and :meth:`flush` methods).
2537
2538
Benjamin Peterson1baf4652009-12-31 03:11:23 +00002539.. currentmodule:: logging
2540
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002541.. class:: StreamHandler(stream=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002542
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002543 Returns a new instance of the :class:`StreamHandler` class. If *stream* is
Georg Brandl116aa622007-08-15 14:28:22 +00002544 specified, the instance will use it for logging output; otherwise, *sys.stderr*
2545 will be used.
2546
2547
Benjamin Petersone41251e2008-04-25 01:59:09 +00002548 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002549
Benjamin Petersone41251e2008-04-25 01:59:09 +00002550 If a formatter is specified, it is used to format the record. The record
2551 is then written to the stream with a trailing newline. If exception
2552 information is present, it is formatted using
2553 :func:`traceback.print_exception` and appended to the stream.
Georg Brandl116aa622007-08-15 14:28:22 +00002554
2555
Benjamin Petersone41251e2008-04-25 01:59:09 +00002556 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00002557
Benjamin Petersone41251e2008-04-25 01:59:09 +00002558 Flushes the stream by calling its :meth:`flush` method. Note that the
2559 :meth:`close` method is inherited from :class:`Handler` and so does
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002560 no output, so an explicit :meth:`flush` call may be needed at times.
Georg Brandl116aa622007-08-15 14:28:22 +00002561
Vinay Sajip05ed6952010-10-20 20:34:09 +00002562.. versionchanged:: 3.2
2563 The ``StreamHandler`` class now has a ``terminator`` attribute, default
2564 value ``"\n"``, which is used as the terminator when writing a formatted
2565 record to a stream. If you don't want this newline termination, you can
2566 set the handler instance's ``terminator`` attribute to the empty string.
Georg Brandl116aa622007-08-15 14:28:22 +00002567
Vinay Sajipd31f3632010-06-29 15:31:15 +00002568.. _file-handler:
2569
Georg Brandl116aa622007-08-15 14:28:22 +00002570FileHandler
2571^^^^^^^^^^^
2572
2573The :class:`FileHandler` class, located in the core :mod:`logging` package,
2574sends logging output to a disk file. It inherits the output functionality from
2575:class:`StreamHandler`.
2576
2577
Vinay Sajipd31f3632010-06-29 15:31:15 +00002578.. class:: FileHandler(filename, mode='a', encoding=None, delay=False)
Georg Brandl116aa622007-08-15 14:28:22 +00002579
2580 Returns a new instance of the :class:`FileHandler` class. The specified file is
2581 opened and used as the stream for logging. If *mode* is not specified,
2582 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Christian Heimese7a15bb2008-01-24 16:21:45 +00002583 with that encoding. If *delay* is true, then file opening is deferred until the
2584 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002585
2586
Benjamin Petersone41251e2008-04-25 01:59:09 +00002587 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002588
Benjamin Petersone41251e2008-04-25 01:59:09 +00002589 Closes the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002590
2591
Benjamin Petersone41251e2008-04-25 01:59:09 +00002592 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002593
Benjamin Petersone41251e2008-04-25 01:59:09 +00002594 Outputs the record to the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002595
Georg Brandl1eb40bc2010-12-03 15:30:09 +00002596
Vinay Sajipd31f3632010-06-29 15:31:15 +00002597.. _null-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002598
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002599NullHandler
2600^^^^^^^^^^^
2601
2602.. versionadded:: 3.1
2603
2604The :class:`NullHandler` class, located in the core :mod:`logging` package,
2605does not do any formatting or output. It is essentially a "no-op" handler
2606for use by library developers.
2607
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002608.. class:: NullHandler()
2609
2610 Returns a new instance of the :class:`NullHandler` class.
2611
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002612 .. method:: emit(record)
2613
2614 This method does nothing.
2615
Vinay Sajip76ca3b42010-09-27 13:53:47 +00002616 .. method:: handle(record)
2617
2618 This method does nothing.
2619
2620 .. method:: createLock()
2621
Senthil Kumaran46a48be2010-10-15 13:10:10 +00002622 This method returns ``None`` for the lock, since there is no
Vinay Sajip76ca3b42010-09-27 13:53:47 +00002623 underlying I/O to which access needs to be serialized.
2624
2625
Vinay Sajip26a2d5e2009-01-10 13:37:26 +00002626See :ref:`library-config` for more information on how to use
2627:class:`NullHandler`.
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00002628
Vinay Sajipd31f3632010-06-29 15:31:15 +00002629.. _watched-file-handler:
2630
Georg Brandl116aa622007-08-15 14:28:22 +00002631WatchedFileHandler
2632^^^^^^^^^^^^^^^^^^
2633
Benjamin Peterson058e31e2009-01-16 03:54:08 +00002634.. currentmodule:: logging.handlers
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002635
Georg Brandl116aa622007-08-15 14:28:22 +00002636The :class:`WatchedFileHandler` class, located in the :mod:`logging.handlers`
2637module, is a :class:`FileHandler` which watches the file it is logging to. If
2638the file changes, it is closed and reopened using the file name.
2639
2640A file change can happen because of usage of programs such as *newsyslog* and
2641*logrotate* which perform log file rotation. This handler, intended for use
2642under Unix/Linux, watches the file to see if it has changed since the last emit.
2643(A file is deemed to have changed if its device or inode have changed.) If the
2644file has changed, the old file stream is closed, and the file opened to get a
2645new stream.
2646
2647This handler is not appropriate for use under Windows, because under Windows
2648open log files cannot be moved or renamed - logging opens the files with
2649exclusive locks - and so there is no need for such a handler. Furthermore,
2650*ST_INO* is not supported under Windows; :func:`stat` always returns zero for
2651this value.
2652
2653
Christian Heimese7a15bb2008-01-24 16:21:45 +00002654.. class:: WatchedFileHandler(filename[,mode[, encoding[, delay]]])
Georg Brandl116aa622007-08-15 14:28:22 +00002655
2656 Returns a new instance of the :class:`WatchedFileHandler` class. The specified
2657 file is opened and used as the stream for logging. If *mode* is not specified,
2658 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Christian Heimese7a15bb2008-01-24 16:21:45 +00002659 with that encoding. If *delay* is true, then file opening is deferred until the
2660 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002661
2662
Benjamin Petersone41251e2008-04-25 01:59:09 +00002663 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002664
Benjamin Petersone41251e2008-04-25 01:59:09 +00002665 Outputs the record to the file, but first checks to see if the file has
2666 changed. If it has, the existing stream is flushed and closed and the
2667 file opened again, before outputting the record to the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002668
Vinay Sajipd31f3632010-06-29 15:31:15 +00002669.. _rotating-file-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002670
2671RotatingFileHandler
2672^^^^^^^^^^^^^^^^^^^
2673
2674The :class:`RotatingFileHandler` class, located in the :mod:`logging.handlers`
2675module, supports rotation of disk log files.
2676
2677
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002678.. class:: RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0)
Georg Brandl116aa622007-08-15 14:28:22 +00002679
2680 Returns a new instance of the :class:`RotatingFileHandler` class. The specified
2681 file is opened and used as the stream for logging. If *mode* is not specified,
Christian Heimese7a15bb2008-01-24 16:21:45 +00002682 ``'a'`` is used. If *encoding* is not *None*, it is used to open the file
2683 with that encoding. If *delay* is true, then file opening is deferred until the
2684 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002685
2686 You can use the *maxBytes* and *backupCount* values to allow the file to
2687 :dfn:`rollover` at a predetermined size. When the size is about to be exceeded,
2688 the file is closed and a new file is silently opened for output. Rollover occurs
2689 whenever the current log file is nearly *maxBytes* in length; if *maxBytes* is
2690 zero, rollover never occurs. If *backupCount* is non-zero, the system will save
2691 old log files by appending the extensions ".1", ".2" etc., to the filename. For
2692 example, with a *backupCount* of 5 and a base file name of :file:`app.log`, you
2693 would get :file:`app.log`, :file:`app.log.1`, :file:`app.log.2`, up to
2694 :file:`app.log.5`. The file being written to is always :file:`app.log`. When
2695 this file is filled, it is closed and renamed to :file:`app.log.1`, and if files
2696 :file:`app.log.1`, :file:`app.log.2`, etc. exist, then they are renamed to
2697 :file:`app.log.2`, :file:`app.log.3` etc. respectively.
2698
2699
Benjamin Petersone41251e2008-04-25 01:59:09 +00002700 .. method:: doRollover()
Georg Brandl116aa622007-08-15 14:28:22 +00002701
Benjamin Petersone41251e2008-04-25 01:59:09 +00002702 Does a rollover, as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002703
2704
Benjamin Petersone41251e2008-04-25 01:59:09 +00002705 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002706
Benjamin Petersone41251e2008-04-25 01:59:09 +00002707 Outputs the record to the file, catering for rollover as described
2708 previously.
Georg Brandl116aa622007-08-15 14:28:22 +00002709
Vinay Sajipd31f3632010-06-29 15:31:15 +00002710.. _timed-rotating-file-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002711
2712TimedRotatingFileHandler
2713^^^^^^^^^^^^^^^^^^^^^^^^
2714
2715The :class:`TimedRotatingFileHandler` class, located in the
2716:mod:`logging.handlers` module, supports rotation of disk log files at certain
2717timed intervals.
2718
2719
Vinay Sajipd31f3632010-06-29 15:31:15 +00002720.. class:: TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False)
Georg Brandl116aa622007-08-15 14:28:22 +00002721
2722 Returns a new instance of the :class:`TimedRotatingFileHandler` class. The
2723 specified file is opened and used as the stream for logging. On rotating it also
2724 sets the filename suffix. Rotating happens based on the product of *when* and
2725 *interval*.
2726
2727 You can use the *when* to specify the type of *interval*. The list of possible
Georg Brandl0c77a822008-06-10 16:37:50 +00002728 values is below. Note that they are not case sensitive.
Georg Brandl116aa622007-08-15 14:28:22 +00002729
Christian Heimesb558a2e2008-03-02 22:46:37 +00002730 +----------------+-----------------------+
2731 | Value | Type of interval |
2732 +================+=======================+
2733 | ``'S'`` | Seconds |
2734 +----------------+-----------------------+
2735 | ``'M'`` | Minutes |
2736 +----------------+-----------------------+
2737 | ``'H'`` | Hours |
2738 +----------------+-----------------------+
2739 | ``'D'`` | Days |
2740 +----------------+-----------------------+
2741 | ``'W'`` | Week day (0=Monday) |
2742 +----------------+-----------------------+
2743 | ``'midnight'`` | Roll over at midnight |
2744 +----------------+-----------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00002745
Christian Heimesb558a2e2008-03-02 22:46:37 +00002746 The system will save old log files by appending extensions to the filename.
2747 The extensions are date-and-time based, using the strftime format
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00002748 ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on the
Georg Brandl3dbca812008-07-23 16:10:53 +00002749 rollover interval.
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00002750
2751 When computing the next rollover time for the first time (when the handler
2752 is created), the last modification time of an existing log file, or else
2753 the current time, is used to compute when the next rotation will occur.
2754
Georg Brandl0c77a822008-06-10 16:37:50 +00002755 If the *utc* argument is true, times in UTC will be used; otherwise
2756 local time is used.
2757
2758 If *backupCount* is nonzero, at most *backupCount* files
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00002759 will be kept, and if more would be created when rollover occurs, the oldest
2760 one is deleted. The deletion logic uses the interval to determine which
2761 files to delete, so changing the interval may leave old files lying around.
Georg Brandl116aa622007-08-15 14:28:22 +00002762
Vinay Sajipd31f3632010-06-29 15:31:15 +00002763 If *delay* is true, then file opening is deferred until the first call to
2764 :meth:`emit`.
2765
Georg Brandl116aa622007-08-15 14:28:22 +00002766
Benjamin Petersone41251e2008-04-25 01:59:09 +00002767 .. method:: doRollover()
Georg Brandl116aa622007-08-15 14:28:22 +00002768
Benjamin Petersone41251e2008-04-25 01:59:09 +00002769 Does a rollover, as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002770
2771
Benjamin Petersone41251e2008-04-25 01:59:09 +00002772 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002773
Benjamin Petersone41251e2008-04-25 01:59:09 +00002774 Outputs the record to the file, catering for rollover as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002775
2776
Vinay Sajipd31f3632010-06-29 15:31:15 +00002777.. _socket-handler:
2778
Georg Brandl116aa622007-08-15 14:28:22 +00002779SocketHandler
2780^^^^^^^^^^^^^
2781
2782The :class:`SocketHandler` class, located in the :mod:`logging.handlers` module,
2783sends logging output to a network socket. The base class uses a TCP socket.
2784
2785
2786.. class:: SocketHandler(host, port)
2787
2788 Returns a new instance of the :class:`SocketHandler` class intended to
2789 communicate with a remote machine whose address is given by *host* and *port*.
2790
2791
Benjamin Petersone41251e2008-04-25 01:59:09 +00002792 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002793
Benjamin Petersone41251e2008-04-25 01:59:09 +00002794 Closes the socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002795
2796
Benjamin Petersone41251e2008-04-25 01:59:09 +00002797 .. method:: emit()
Georg Brandl116aa622007-08-15 14:28:22 +00002798
Benjamin Petersone41251e2008-04-25 01:59:09 +00002799 Pickles the record's attribute dictionary and writes it to the socket in
2800 binary format. If there is an error with the socket, silently drops the
2801 packet. If the connection was previously lost, re-establishes the
2802 connection. To unpickle the record at the receiving end into a
2803 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl116aa622007-08-15 14:28:22 +00002804
2805
Benjamin Petersone41251e2008-04-25 01:59:09 +00002806 .. method:: handleError()
Georg Brandl116aa622007-08-15 14:28:22 +00002807
Benjamin Petersone41251e2008-04-25 01:59:09 +00002808 Handles an error which has occurred during :meth:`emit`. The most likely
2809 cause is a lost connection. Closes the socket so that we can retry on the
2810 next event.
Georg Brandl116aa622007-08-15 14:28:22 +00002811
2812
Benjamin Petersone41251e2008-04-25 01:59:09 +00002813 .. method:: makeSocket()
Georg Brandl116aa622007-08-15 14:28:22 +00002814
Benjamin Petersone41251e2008-04-25 01:59:09 +00002815 This is a factory method which allows subclasses to define the precise
2816 type of socket they want. The default implementation creates a TCP socket
2817 (:const:`socket.SOCK_STREAM`).
Georg Brandl116aa622007-08-15 14:28:22 +00002818
2819
Benjamin Petersone41251e2008-04-25 01:59:09 +00002820 .. method:: makePickle(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002821
Benjamin Petersone41251e2008-04-25 01:59:09 +00002822 Pickles the record's attribute dictionary in binary format with a length
2823 prefix, and returns it ready for transmission across the socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002824
Vinay Sajipd31f3632010-06-29 15:31:15 +00002825 Note that pickles aren't completely secure. If you are concerned about
2826 security, you may want to override this method to implement a more secure
2827 mechanism. For example, you can sign pickles using HMAC and then verify
2828 them on the receiving end, or alternatively you can disable unpickling of
2829 global objects on the receiving end.
Georg Brandl116aa622007-08-15 14:28:22 +00002830
Benjamin Petersone41251e2008-04-25 01:59:09 +00002831 .. method:: send(packet)
Georg Brandl116aa622007-08-15 14:28:22 +00002832
Benjamin Petersone41251e2008-04-25 01:59:09 +00002833 Send a pickled string *packet* to the socket. This function allows for
2834 partial sends which can happen when the network is busy.
Georg Brandl116aa622007-08-15 14:28:22 +00002835
2836
Vinay Sajipd31f3632010-06-29 15:31:15 +00002837.. _datagram-handler:
2838
Georg Brandl116aa622007-08-15 14:28:22 +00002839DatagramHandler
2840^^^^^^^^^^^^^^^
2841
2842The :class:`DatagramHandler` class, located in the :mod:`logging.handlers`
2843module, inherits from :class:`SocketHandler` to support sending logging messages
2844over UDP sockets.
2845
2846
2847.. class:: DatagramHandler(host, port)
2848
2849 Returns a new instance of the :class:`DatagramHandler` class intended to
2850 communicate with a remote machine whose address is given by *host* and *port*.
2851
2852
Benjamin Petersone41251e2008-04-25 01:59:09 +00002853 .. method:: emit()
Georg Brandl116aa622007-08-15 14:28:22 +00002854
Benjamin Petersone41251e2008-04-25 01:59:09 +00002855 Pickles the record's attribute dictionary and writes it to the socket in
2856 binary format. If there is an error with the socket, silently drops the
2857 packet. To unpickle the record at the receiving end into a
2858 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl116aa622007-08-15 14:28:22 +00002859
2860
Benjamin Petersone41251e2008-04-25 01:59:09 +00002861 .. method:: makeSocket()
Georg Brandl116aa622007-08-15 14:28:22 +00002862
Benjamin Petersone41251e2008-04-25 01:59:09 +00002863 The factory method of :class:`SocketHandler` is here overridden to create
2864 a UDP socket (:const:`socket.SOCK_DGRAM`).
Georg Brandl116aa622007-08-15 14:28:22 +00002865
2866
Benjamin Petersone41251e2008-04-25 01:59:09 +00002867 .. method:: send(s)
Georg Brandl116aa622007-08-15 14:28:22 +00002868
Benjamin Petersone41251e2008-04-25 01:59:09 +00002869 Send a pickled string to a socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002870
2871
Vinay Sajipd31f3632010-06-29 15:31:15 +00002872.. _syslog-handler:
2873
Georg Brandl116aa622007-08-15 14:28:22 +00002874SysLogHandler
2875^^^^^^^^^^^^^
2876
2877The :class:`SysLogHandler` class, located in the :mod:`logging.handlers` module,
2878supports sending logging messages to a remote or local Unix syslog.
2879
2880
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002881.. class:: SysLogHandler(address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER, socktype=socket.SOCK_DGRAM)
Georg Brandl116aa622007-08-15 14:28:22 +00002882
2883 Returns a new instance of the :class:`SysLogHandler` class intended to
2884 communicate with a remote Unix machine whose address is given by *address* in
2885 the form of a ``(host, port)`` tuple. If *address* is not specified,
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002886 ``('localhost', 514)`` is used. The address is used to open a socket. An
Georg Brandl116aa622007-08-15 14:28:22 +00002887 alternative to providing a ``(host, port)`` tuple is providing an address as a
2888 string, for example "/dev/log". In this case, a Unix domain socket is used to
2889 send the message to the syslog. If *facility* is not specified,
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002890 :const:`LOG_USER` is used. The type of socket opened depends on the
2891 *socktype* argument, which defaults to :const:`socket.SOCK_DGRAM` and thus
2892 opens a UDP socket. To open a TCP socket (for use with the newer syslog
2893 daemons such as rsyslog), specify a value of :const:`socket.SOCK_STREAM`.
2894
Vinay Sajip972412d2010-09-23 20:31:24 +00002895 Note that if your server is not listening on UDP port 514,
2896 :class:`SysLogHandler` may appear not to work. In that case, check what
2897 address you should be using for a domain socket - it's system dependent.
2898 For example, on Linux it's usually "/dev/log" but on OS/X it's
2899 "/var/run/syslog". You'll need to check your platform and use the
2900 appropriate address (you may need to do this check at runtime if your
2901 application needs to run on several platforms). On Windows, you pretty
2902 much have to use the UDP option.
2903
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002904 .. versionchanged:: 3.2
2905 *socktype* was added.
Georg Brandl116aa622007-08-15 14:28:22 +00002906
2907
Benjamin Petersone41251e2008-04-25 01:59:09 +00002908 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002909
Benjamin Petersone41251e2008-04-25 01:59:09 +00002910 Closes the socket to the remote host.
Georg Brandl116aa622007-08-15 14:28:22 +00002911
2912
Benjamin Petersone41251e2008-04-25 01:59:09 +00002913 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002914
Benjamin Petersone41251e2008-04-25 01:59:09 +00002915 The record is formatted, and then sent to the syslog server. If exception
2916 information is present, it is *not* sent to the server.
Georg Brandl116aa622007-08-15 14:28:22 +00002917
2918
Benjamin Petersone41251e2008-04-25 01:59:09 +00002919 .. method:: encodePriority(facility, priority)
Georg Brandl116aa622007-08-15 14:28:22 +00002920
Benjamin Petersone41251e2008-04-25 01:59:09 +00002921 Encodes the facility and priority into an integer. You can pass in strings
2922 or integers - if strings are passed, internal mapping dictionaries are
2923 used to convert them to integers.
Georg Brandl116aa622007-08-15 14:28:22 +00002924
Benjamin Peterson22005fc2010-04-11 16:25:06 +00002925 The symbolic ``LOG_`` values are defined in :class:`SysLogHandler` and
2926 mirror the values defined in the ``sys/syslog.h`` header file.
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002927
Georg Brandl88d7dbd2010-04-18 09:50:07 +00002928 **Priorities**
2929
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002930 +--------------------------+---------------+
2931 | Name (string) | Symbolic value|
2932 +==========================+===============+
2933 | ``alert`` | LOG_ALERT |
2934 +--------------------------+---------------+
2935 | ``crit`` or ``critical`` | LOG_CRIT |
2936 +--------------------------+---------------+
2937 | ``debug`` | LOG_DEBUG |
2938 +--------------------------+---------------+
2939 | ``emerg`` or ``panic`` | LOG_EMERG |
2940 +--------------------------+---------------+
2941 | ``err`` or ``error`` | LOG_ERR |
2942 +--------------------------+---------------+
2943 | ``info`` | LOG_INFO |
2944 +--------------------------+---------------+
2945 | ``notice`` | LOG_NOTICE |
2946 +--------------------------+---------------+
2947 | ``warn`` or ``warning`` | LOG_WARNING |
2948 +--------------------------+---------------+
2949
Georg Brandl88d7dbd2010-04-18 09:50:07 +00002950 **Facilities**
2951
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002952 +---------------+---------------+
2953 | Name (string) | Symbolic value|
2954 +===============+===============+
2955 | ``auth`` | LOG_AUTH |
2956 +---------------+---------------+
2957 | ``authpriv`` | LOG_AUTHPRIV |
2958 +---------------+---------------+
2959 | ``cron`` | LOG_CRON |
2960 +---------------+---------------+
2961 | ``daemon`` | LOG_DAEMON |
2962 +---------------+---------------+
2963 | ``ftp`` | LOG_FTP |
2964 +---------------+---------------+
2965 | ``kern`` | LOG_KERN |
2966 +---------------+---------------+
2967 | ``lpr`` | LOG_LPR |
2968 +---------------+---------------+
2969 | ``mail`` | LOG_MAIL |
2970 +---------------+---------------+
2971 | ``news`` | LOG_NEWS |
2972 +---------------+---------------+
2973 | ``syslog`` | LOG_SYSLOG |
2974 +---------------+---------------+
2975 | ``user`` | LOG_USER |
2976 +---------------+---------------+
2977 | ``uucp`` | LOG_UUCP |
2978 +---------------+---------------+
2979 | ``local0`` | LOG_LOCAL0 |
2980 +---------------+---------------+
2981 | ``local1`` | LOG_LOCAL1 |
2982 +---------------+---------------+
2983 | ``local2`` | LOG_LOCAL2 |
2984 +---------------+---------------+
2985 | ``local3`` | LOG_LOCAL3 |
2986 +---------------+---------------+
2987 | ``local4`` | LOG_LOCAL4 |
2988 +---------------+---------------+
2989 | ``local5`` | LOG_LOCAL5 |
2990 +---------------+---------------+
2991 | ``local6`` | LOG_LOCAL6 |
2992 +---------------+---------------+
2993 | ``local7`` | LOG_LOCAL7 |
2994 +---------------+---------------+
2995
2996 .. method:: mapPriority(levelname)
2997
2998 Maps a logging level name to a syslog priority name.
2999 You may need to override this if you are using custom levels, or
3000 if the default algorithm is not suitable for your needs. The
3001 default algorithm maps ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and
3002 ``CRITICAL`` to the equivalent syslog names, and all other level
3003 names to "warning".
3004
3005.. _nt-eventlog-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00003006
3007NTEventLogHandler
3008^^^^^^^^^^^^^^^^^
3009
3010The :class:`NTEventLogHandler` class, located in the :mod:`logging.handlers`
3011module, supports sending logging messages to a local Windows NT, Windows 2000 or
3012Windows XP event log. Before you can use it, you need Mark Hammond's Win32
3013extensions for Python installed.
3014
3015
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003016.. class:: NTEventLogHandler(appname, dllname=None, logtype='Application')
Georg Brandl116aa622007-08-15 14:28:22 +00003017
3018 Returns a new instance of the :class:`NTEventLogHandler` class. The *appname* is
3019 used to define the application name as it appears in the event log. An
3020 appropriate registry entry is created using this name. The *dllname* should give
3021 the fully qualified pathname of a .dll or .exe which contains message
3022 definitions to hold in the log (if not specified, ``'win32service.pyd'`` is used
3023 - this is installed with the Win32 extensions and contains some basic
3024 placeholder message definitions. Note that use of these placeholders will make
3025 your event logs big, as the entire message source is held in the log. If you
3026 want slimmer logs, you have to pass in the name of your own .dll or .exe which
3027 contains the message definitions you want to use in the event log). The
3028 *logtype* is one of ``'Application'``, ``'System'`` or ``'Security'``, and
3029 defaults to ``'Application'``.
3030
3031
Benjamin Petersone41251e2008-04-25 01:59:09 +00003032 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00003033
Benjamin Petersone41251e2008-04-25 01:59:09 +00003034 At this point, you can remove the application name from the registry as a
3035 source of event log entries. However, if you do this, you will not be able
3036 to see the events as you intended in the Event Log Viewer - it needs to be
3037 able to access the registry to get the .dll name. The current version does
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00003038 not do this.
Georg Brandl116aa622007-08-15 14:28:22 +00003039
3040
Benjamin Petersone41251e2008-04-25 01:59:09 +00003041 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003042
Benjamin Petersone41251e2008-04-25 01:59:09 +00003043 Determines the message ID, event category and event type, and then logs
3044 the message in the NT event log.
Georg Brandl116aa622007-08-15 14:28:22 +00003045
3046
Benjamin Petersone41251e2008-04-25 01:59:09 +00003047 .. method:: getEventCategory(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003048
Benjamin Petersone41251e2008-04-25 01:59:09 +00003049 Returns the event category for the record. Override this if you want to
3050 specify your own categories. This version returns 0.
Georg Brandl116aa622007-08-15 14:28:22 +00003051
3052
Benjamin Petersone41251e2008-04-25 01:59:09 +00003053 .. method:: getEventType(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003054
Benjamin Petersone41251e2008-04-25 01:59:09 +00003055 Returns the event type for the record. Override this if you want to
3056 specify your own types. This version does a mapping using the handler's
3057 typemap attribute, which is set up in :meth:`__init__` to a dictionary
3058 which contains mappings for :const:`DEBUG`, :const:`INFO`,
3059 :const:`WARNING`, :const:`ERROR` and :const:`CRITICAL`. If you are using
3060 your own levels, you will either need to override this method or place a
3061 suitable dictionary in the handler's *typemap* attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00003062
3063
Benjamin Petersone41251e2008-04-25 01:59:09 +00003064 .. method:: getMessageID(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003065
Benjamin Petersone41251e2008-04-25 01:59:09 +00003066 Returns the message ID for the record. If you are using your own messages,
3067 you could do this by having the *msg* passed to the logger being an ID
3068 rather than a format string. Then, in here, you could use a dictionary
3069 lookup to get the message ID. This version returns 1, which is the base
3070 message ID in :file:`win32service.pyd`.
Georg Brandl116aa622007-08-15 14:28:22 +00003071
Vinay Sajipd31f3632010-06-29 15:31:15 +00003072.. _smtp-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00003073
3074SMTPHandler
3075^^^^^^^^^^^
3076
3077The :class:`SMTPHandler` class, located in the :mod:`logging.handlers` module,
3078supports sending logging messages to an email address via SMTP.
3079
3080
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003081.. class:: SMTPHandler(mailhost, fromaddr, toaddrs, subject, credentials=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003082
3083 Returns a new instance of the :class:`SMTPHandler` class. The instance is
3084 initialized with the from and to addresses and subject line of the email. The
3085 *toaddrs* should be a list of strings. To specify a non-standard SMTP port, use
3086 the (host, port) tuple format for the *mailhost* argument. If you use a string,
3087 the standard SMTP port is used. If your SMTP server requires authentication, you
3088 can specify a (username, password) tuple for the *credentials* argument.
3089
Georg Brandl116aa622007-08-15 14:28:22 +00003090
Benjamin Petersone41251e2008-04-25 01:59:09 +00003091 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003092
Benjamin Petersone41251e2008-04-25 01:59:09 +00003093 Formats the record and sends it to the specified addressees.
Georg Brandl116aa622007-08-15 14:28:22 +00003094
3095
Benjamin Petersone41251e2008-04-25 01:59:09 +00003096 .. method:: getSubject(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003097
Benjamin Petersone41251e2008-04-25 01:59:09 +00003098 If you want to specify a subject line which is record-dependent, override
3099 this method.
Georg Brandl116aa622007-08-15 14:28:22 +00003100
Vinay Sajipd31f3632010-06-29 15:31:15 +00003101.. _memory-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00003102
3103MemoryHandler
3104^^^^^^^^^^^^^
3105
3106The :class:`MemoryHandler` class, located in the :mod:`logging.handlers` module,
3107supports buffering of logging records in memory, periodically flushing them to a
3108:dfn:`target` handler. Flushing occurs whenever the buffer is full, or when an
3109event of a certain severity or greater is seen.
3110
3111:class:`MemoryHandler` is a subclass of the more general
3112:class:`BufferingHandler`, which is an abstract class. This buffers logging
3113records in memory. Whenever each record is added to the buffer, a check is made
3114by calling :meth:`shouldFlush` to see if the buffer should be flushed. If it
3115should, then :meth:`flush` is expected to do the needful.
3116
3117
3118.. class:: BufferingHandler(capacity)
3119
3120 Initializes the handler with a buffer of the specified capacity.
3121
3122
Benjamin Petersone41251e2008-04-25 01:59:09 +00003123 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003124
Benjamin Petersone41251e2008-04-25 01:59:09 +00003125 Appends the record to the buffer. If :meth:`shouldFlush` returns true,
3126 calls :meth:`flush` to process the buffer.
Georg Brandl116aa622007-08-15 14:28:22 +00003127
3128
Benjamin Petersone41251e2008-04-25 01:59:09 +00003129 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00003130
Benjamin Petersone41251e2008-04-25 01:59:09 +00003131 You can override this to implement custom flushing behavior. This version
3132 just zaps the buffer to empty.
Georg Brandl116aa622007-08-15 14:28:22 +00003133
3134
Benjamin Petersone41251e2008-04-25 01:59:09 +00003135 .. method:: shouldFlush(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003136
Benjamin Petersone41251e2008-04-25 01:59:09 +00003137 Returns true if the buffer is up to capacity. This method can be
3138 overridden to implement custom flushing strategies.
Georg Brandl116aa622007-08-15 14:28:22 +00003139
3140
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003141.. class:: MemoryHandler(capacity, flushLevel=ERROR, target=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003142
3143 Returns a new instance of the :class:`MemoryHandler` class. The instance is
3144 initialized with a buffer size of *capacity*. If *flushLevel* is not specified,
3145 :const:`ERROR` is used. If no *target* is specified, the target will need to be
3146 set using :meth:`setTarget` before this handler does anything useful.
3147
3148
Benjamin Petersone41251e2008-04-25 01:59:09 +00003149 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00003150
Benjamin Petersone41251e2008-04-25 01:59:09 +00003151 Calls :meth:`flush`, sets the target to :const:`None` and clears the
3152 buffer.
Georg Brandl116aa622007-08-15 14:28:22 +00003153
3154
Benjamin Petersone41251e2008-04-25 01:59:09 +00003155 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00003156
Benjamin Petersone41251e2008-04-25 01:59:09 +00003157 For a :class:`MemoryHandler`, flushing means just sending the buffered
Vinay Sajipc84f0162010-09-21 11:25:39 +00003158 records to the target, if there is one. The buffer is also cleared when
3159 this happens. Override if you want different behavior.
Georg Brandl116aa622007-08-15 14:28:22 +00003160
3161
Benjamin Petersone41251e2008-04-25 01:59:09 +00003162 .. method:: setTarget(target)
Georg Brandl116aa622007-08-15 14:28:22 +00003163
Benjamin Petersone41251e2008-04-25 01:59:09 +00003164 Sets the target handler for this handler.
Georg Brandl116aa622007-08-15 14:28:22 +00003165
3166
Benjamin Petersone41251e2008-04-25 01:59:09 +00003167 .. method:: shouldFlush(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003168
Benjamin Petersone41251e2008-04-25 01:59:09 +00003169 Checks for buffer full or a record at the *flushLevel* or higher.
Georg Brandl116aa622007-08-15 14:28:22 +00003170
3171
Vinay Sajipd31f3632010-06-29 15:31:15 +00003172.. _http-handler:
3173
Georg Brandl116aa622007-08-15 14:28:22 +00003174HTTPHandler
3175^^^^^^^^^^^
3176
3177The :class:`HTTPHandler` class, located in the :mod:`logging.handlers` module,
3178supports sending logging messages to a Web server, using either ``GET`` or
3179``POST`` semantics.
3180
3181
Vinay Sajip1b5646a2010-09-13 20:37:50 +00003182.. class:: HTTPHandler(host, url, method='GET', secure=False, credentials=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003183
Vinay Sajip1b5646a2010-09-13 20:37:50 +00003184 Returns a new instance of the :class:`HTTPHandler` class. The *host* can be
3185 of the form ``host:port``, should you need to use a specific port number.
3186 If no *method* is specified, ``GET`` is used. If *secure* is True, an HTTPS
3187 connection will be used. If *credentials* is specified, it should be a
3188 2-tuple consisting of userid and password, which will be placed in an HTTP
3189 'Authorization' header using Basic authentication. If you specify
3190 credentials, you should also specify secure=True so that your userid and
3191 password are not passed in cleartext across the wire.
Georg Brandl116aa622007-08-15 14:28:22 +00003192
3193
Benjamin Petersone41251e2008-04-25 01:59:09 +00003194 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003195
Senthil Kumaranf0769e82010-08-09 19:53:52 +00003196 Sends the record to the Web server as a percent-encoded dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00003197
3198
Vinay Sajip121a1c42010-09-08 10:46:15 +00003199.. _queue-handler:
3200
3201
3202QueueHandler
3203^^^^^^^^^^^^
3204
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003205.. versionadded:: 3.2
3206
Vinay Sajip121a1c42010-09-08 10:46:15 +00003207The :class:`QueueHandler` class, located in the :mod:`logging.handlers` module,
3208supports sending logging messages to a queue, such as those implemented in the
3209:mod:`queue` or :mod:`multiprocessing` modules.
3210
Vinay Sajip0637d492010-09-23 08:15:54 +00003211Along with the :class:`QueueListener` class, :class:`QueueHandler` can be used
3212to let handlers do their work on a separate thread from the one which does the
3213logging. This is important in Web applications and also other service
3214applications where threads servicing clients need to respond as quickly as
3215possible, while any potentially slow operations (such as sending an email via
3216:class:`SMTPHandler`) are done on a separate thread.
Vinay Sajip121a1c42010-09-08 10:46:15 +00003217
3218.. class:: QueueHandler(queue)
3219
3220 Returns a new instance of the :class:`QueueHandler` class. The instance is
Vinay Sajip63891ed2010-09-13 20:02:39 +00003221 initialized with the queue to send messages to. The queue can be any queue-
Vinay Sajip0637d492010-09-23 08:15:54 +00003222 like object; it's used as-is by the :meth:`enqueue` method, which needs
Vinay Sajip63891ed2010-09-13 20:02:39 +00003223 to know how to send messages to it.
Vinay Sajip121a1c42010-09-08 10:46:15 +00003224
3225
3226 .. method:: emit(record)
3227
Vinay Sajip0258ce82010-09-22 20:34:53 +00003228 Enqueues the result of preparing the LogRecord.
3229
3230 .. method:: prepare(record)
3231
3232 Prepares a record for queuing. The object returned by this
3233 method is enqueued.
3234
3235 The base implementation formats the record to merge the message
3236 and arguments, and removes unpickleable items from the record
3237 in-place.
3238
3239 You might want to override this method if you want to convert
3240 the record to a dict or JSON string, or send a modified copy
3241 of the record while leaving the original intact.
Vinay Sajip121a1c42010-09-08 10:46:15 +00003242
3243 .. method:: enqueue(record)
3244
3245 Enqueues the record on the queue using ``put_nowait()``; you may
3246 want to override this if you want to use blocking behaviour, or a
3247 timeout, or a customised queue implementation.
3248
3249
Vinay Sajip121a1c42010-09-08 10:46:15 +00003250
Vinay Sajip0637d492010-09-23 08:15:54 +00003251.. queue-listener:
3252
3253QueueListener
3254^^^^^^^^^^^^^
3255
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003256.. versionadded:: 3.2
3257
Vinay Sajip0637d492010-09-23 08:15:54 +00003258The :class:`QueueListener` class, located in the :mod:`logging.handlers`
3259module, supports receiving logging messages from a queue, such as those
3260implemented in the :mod:`queue` or :mod:`multiprocessing` modules. The
3261messages are received from a queue in an internal thread and passed, on
3262the same thread, to one or more handlers for processing.
3263
3264Along with the :class:`QueueHandler` class, :class:`QueueListener` can be used
3265to let handlers do their work on a separate thread from the one which does the
3266logging. This is important in Web applications and also other service
3267applications where threads servicing clients need to respond as quickly as
3268possible, while any potentially slow operations (such as sending an email via
3269:class:`SMTPHandler`) are done on a separate thread.
3270
3271.. class:: QueueListener(queue, *handlers)
3272
3273 Returns a new instance of the :class:`QueueListener` class. The instance is
3274 initialized with the queue to send messages to and a list of handlers which
3275 will handle entries placed on the queue. The queue can be any queue-
3276 like object; it's passed as-is to the :meth:`dequeue` method, which needs
3277 to know how to get messages from it.
3278
3279 .. method:: dequeue(block)
3280
3281 Dequeues a record and return it, optionally blocking.
3282
3283 The base implementation uses ``get()``. You may want to override this
3284 method if you want to use timeouts or work with custom queue
3285 implementations.
3286
3287 .. method:: prepare(record)
3288
3289 Prepare a record for handling.
3290
3291 This implementation just returns the passed-in record. You may want to
3292 override this method if you need to do any custom marshalling or
3293 manipulation of the record before passing it to the handlers.
3294
3295 .. method:: handle(record)
3296
3297 Handle a record.
3298
3299 This just loops through the handlers offering them the record
3300 to handle. The actual object passed to the handlers is that which
3301 is returned from :meth:`prepare`.
3302
3303 .. method:: start()
3304
3305 Starts the listener.
3306
3307 This starts up a background thread to monitor the queue for
3308 LogRecords to process.
3309
3310 .. method:: stop()
3311
3312 Stops the listener.
3313
3314 This asks the thread to terminate, and then waits for it to do so.
3315 Note that if you don't call this before your application exits, there
3316 may be some records still left on the queue, which won't be processed.
3317
Vinay Sajip0637d492010-09-23 08:15:54 +00003318
Vinay Sajip63891ed2010-09-13 20:02:39 +00003319.. _zeromq-handlers:
3320
Vinay Sajip0637d492010-09-23 08:15:54 +00003321Subclassing QueueHandler
3322^^^^^^^^^^^^^^^^^^^^^^^^
3323
Vinay Sajip63891ed2010-09-13 20:02:39 +00003324You can use a :class:`QueueHandler` subclass to send messages to other kinds
3325of queues, for example a ZeroMQ "publish" socket. In the example below,the
3326socket is created separately and passed to the handler (as its 'queue')::
3327
3328 import zmq # using pyzmq, the Python binding for ZeroMQ
3329 import json # for serializing records portably
3330
3331 ctx = zmq.Context()
3332 sock = zmq.Socket(ctx, zmq.PUB) # or zmq.PUSH, or other suitable value
3333 sock.bind('tcp://*:5556') # or wherever
3334
3335 class ZeroMQSocketHandler(QueueHandler):
3336 def enqueue(self, record):
3337 data = json.dumps(record.__dict__)
3338 self.queue.send(data)
3339
Vinay Sajip0055c422010-09-14 09:42:39 +00003340 handler = ZeroMQSocketHandler(sock)
3341
3342
Vinay Sajip63891ed2010-09-13 20:02:39 +00003343Of course there are other ways of organizing this, for example passing in the
3344data needed by the handler to create the socket::
3345
3346 class ZeroMQSocketHandler(QueueHandler):
3347 def __init__(self, uri, socktype=zmq.PUB, ctx=None):
3348 self.ctx = ctx or zmq.Context()
3349 socket = zmq.Socket(self.ctx, socktype)
Vinay Sajip0637d492010-09-23 08:15:54 +00003350 socket.bind(uri)
Vinay Sajip0055c422010-09-14 09:42:39 +00003351 QueueHandler.__init__(self, socket)
Vinay Sajip63891ed2010-09-13 20:02:39 +00003352
3353 def enqueue(self, record):
3354 data = json.dumps(record.__dict__)
3355 self.queue.send(data)
3356
Vinay Sajipde726922010-09-14 06:59:24 +00003357 def close(self):
3358 self.queue.close()
Vinay Sajip121a1c42010-09-08 10:46:15 +00003359
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003360
Vinay Sajip0637d492010-09-23 08:15:54 +00003361Subclassing QueueListener
3362^^^^^^^^^^^^^^^^^^^^^^^^^
3363
3364You can also subclass :class:`QueueListener` to get messages from other kinds
3365of queues, for example a ZeroMQ "subscribe" socket. Here's an example::
3366
3367 class ZeroMQSocketListener(QueueListener):
3368 def __init__(self, uri, *handlers, **kwargs):
3369 self.ctx = kwargs.get('ctx') or zmq.Context()
3370 socket = zmq.Socket(self.ctx, zmq.SUB)
3371 socket.setsockopt(zmq.SUBSCRIBE, '') # subscribe to everything
3372 socket.connect(uri)
3373
3374 def dequeue(self):
3375 msg = self.queue.recv()
3376 return logging.makeLogRecord(json.loads(msg))
3377
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003378
Christian Heimes8b0facf2007-12-04 19:30:01 +00003379.. _formatter-objects:
3380
Georg Brandl116aa622007-08-15 14:28:22 +00003381Formatter Objects
3382-----------------
3383
Benjamin Peterson75edad02009-01-01 15:05:06 +00003384.. currentmodule:: logging
3385
Georg Brandl116aa622007-08-15 14:28:22 +00003386:class:`Formatter`\ s have the following attributes and methods. They are
3387responsible for converting a :class:`LogRecord` to (usually) a string which can
3388be interpreted by either a human or an external system. The base
3389:class:`Formatter` allows a formatting string to be specified. If none is
3390supplied, the default value of ``'%(message)s'`` is used.
3391
3392A Formatter can be initialized with a format string which makes use of knowledge
3393of the :class:`LogRecord` attributes - such as the default value mentioned above
3394making use of the fact that the user's message and arguments are pre-formatted
3395into a :class:`LogRecord`'s *message* attribute. This format string contains
Ezio Melotti0639d5a2009-12-19 23:26:38 +00003396standard Python %-style mapping keys. See section :ref:`old-string-formatting`
Georg Brandl116aa622007-08-15 14:28:22 +00003397for more information on string formatting.
3398
3399Currently, the useful mapping keys in a :class:`LogRecord` are:
3400
3401+-------------------------+-----------------------------------------------+
3402| Format | Description |
3403+=========================+===============================================+
3404| ``%(name)s`` | Name of the logger (logging channel). |
3405+-------------------------+-----------------------------------------------+
3406| ``%(levelno)s`` | Numeric logging level for the message |
3407| | (:const:`DEBUG`, :const:`INFO`, |
3408| | :const:`WARNING`, :const:`ERROR`, |
3409| | :const:`CRITICAL`). |
3410+-------------------------+-----------------------------------------------+
3411| ``%(levelname)s`` | Text logging level for the message |
3412| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
3413| | ``'ERROR'``, ``'CRITICAL'``). |
3414+-------------------------+-----------------------------------------------+
3415| ``%(pathname)s`` | Full pathname of the source file where the |
3416| | logging call was issued (if available). |
3417+-------------------------+-----------------------------------------------+
3418| ``%(filename)s`` | Filename portion of pathname. |
3419+-------------------------+-----------------------------------------------+
3420| ``%(module)s`` | Module (name portion of filename). |
3421+-------------------------+-----------------------------------------------+
3422| ``%(funcName)s`` | Name of function containing the logging call. |
3423+-------------------------+-----------------------------------------------+
3424| ``%(lineno)d`` | Source line number where the logging call was |
3425| | issued (if available). |
3426+-------------------------+-----------------------------------------------+
3427| ``%(created)f`` | Time when the :class:`LogRecord` was created |
3428| | (as returned by :func:`time.time`). |
3429+-------------------------+-----------------------------------------------+
3430| ``%(relativeCreated)d`` | Time in milliseconds when the LogRecord was |
3431| | created, relative to the time the logging |
3432| | module was loaded. |
3433+-------------------------+-----------------------------------------------+
3434| ``%(asctime)s`` | Human-readable time when the |
3435| | :class:`LogRecord` was created. By default |
3436| | this is of the form "2003-07-08 16:49:45,896" |
3437| | (the numbers after the comma are millisecond |
3438| | portion of the time). |
3439+-------------------------+-----------------------------------------------+
3440| ``%(msecs)d`` | Millisecond portion of the time when the |
3441| | :class:`LogRecord` was created. |
3442+-------------------------+-----------------------------------------------+
3443| ``%(thread)d`` | Thread ID (if available). |
3444+-------------------------+-----------------------------------------------+
3445| ``%(threadName)s`` | Thread name (if available). |
3446+-------------------------+-----------------------------------------------+
3447| ``%(process)d`` | Process ID (if available). |
3448+-------------------------+-----------------------------------------------+
Vinay Sajip121a1c42010-09-08 10:46:15 +00003449| ``%(processName)s`` | Process name (if available). |
3450+-------------------------+-----------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00003451| ``%(message)s`` | The logged message, computed as ``msg % |
3452| | args``. |
3453+-------------------------+-----------------------------------------------+
3454
Georg Brandl116aa622007-08-15 14:28:22 +00003455
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003456.. class:: Formatter(fmt=None, datefmt=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003457
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003458 Returns a new instance of the :class:`Formatter` class. The instance is
3459 initialized with a format string for the message as a whole, as well as a
3460 format string for the date/time portion of a message. If no *fmt* is
3461 specified, ``'%(message)s'`` is used. If no *datefmt* is specified, the
3462 ISO8601 date format is used.
Georg Brandl116aa622007-08-15 14:28:22 +00003463
Benjamin Petersone41251e2008-04-25 01:59:09 +00003464 .. method:: format(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003465
Benjamin Petersone41251e2008-04-25 01:59:09 +00003466 The record's attribute dictionary is used as the operand to a string
3467 formatting operation. Returns the resulting string. Before formatting the
3468 dictionary, a couple of preparatory steps are carried out. The *message*
3469 attribute of the record is computed using *msg* % *args*. If the
3470 formatting string contains ``'(asctime)'``, :meth:`formatTime` is called
3471 to format the event time. If there is exception information, it is
3472 formatted using :meth:`formatException` and appended to the message. Note
3473 that the formatted exception information is cached in attribute
3474 *exc_text*. This is useful because the exception information can be
3475 pickled and sent across the wire, but you should be careful if you have
3476 more than one :class:`Formatter` subclass which customizes the formatting
3477 of exception information. In this case, you will have to clear the cached
3478 value after a formatter has done its formatting, so that the next
3479 formatter to handle the event doesn't use the cached value but
3480 recalculates it afresh.
Georg Brandl116aa622007-08-15 14:28:22 +00003481
Vinay Sajip8593ae62010-11-14 21:33:04 +00003482 If stack information is available, it's appended after the exception
3483 information, using :meth:`formatStack` to transform it if necessary.
3484
Georg Brandl116aa622007-08-15 14:28:22 +00003485
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003486 .. method:: formatTime(record, datefmt=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003487
Benjamin Petersone41251e2008-04-25 01:59:09 +00003488 This method should be called from :meth:`format` by a formatter which
3489 wants to make use of a formatted time. This method can be overridden in
3490 formatters to provide for any specific requirement, but the basic behavior
3491 is as follows: if *datefmt* (a string) is specified, it is used with
3492 :func:`time.strftime` to format the creation time of the
3493 record. Otherwise, the ISO8601 format is used. The resulting string is
3494 returned.
Georg Brandl116aa622007-08-15 14:28:22 +00003495
3496
Benjamin Petersone41251e2008-04-25 01:59:09 +00003497 .. method:: formatException(exc_info)
Georg Brandl116aa622007-08-15 14:28:22 +00003498
Benjamin Petersone41251e2008-04-25 01:59:09 +00003499 Formats the specified exception information (a standard exception tuple as
3500 returned by :func:`sys.exc_info`) as a string. This default implementation
3501 just uses :func:`traceback.print_exception`. The resulting string is
3502 returned.
Georg Brandl116aa622007-08-15 14:28:22 +00003503
Vinay Sajip8593ae62010-11-14 21:33:04 +00003504 .. method:: formatStack(stack_info)
3505
3506 Formats the specified stack information (a string as returned by
3507 :func:`traceback.print_stack`, but with the last newline removed) as a
3508 string. This default implementation just returns the input value.
3509
Vinay Sajipd31f3632010-06-29 15:31:15 +00003510.. _filter:
Georg Brandl116aa622007-08-15 14:28:22 +00003511
3512Filter Objects
3513--------------
3514
Georg Brandl5c66bca2010-10-29 05:36:28 +00003515``Filters`` can be used by ``Handlers`` and ``Loggers`` for more sophisticated
Vinay Sajipfc082ca2010-10-19 21:13:49 +00003516filtering than is provided by levels. The base filter class only allows events
3517which are below a certain point in the logger hierarchy. For example, a filter
3518initialized with "A.B" will allow events logged by loggers "A.B", "A.B.C",
3519"A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If initialized with the
3520empty string, all events are passed.
Georg Brandl116aa622007-08-15 14:28:22 +00003521
3522
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003523.. class:: Filter(name='')
Georg Brandl116aa622007-08-15 14:28:22 +00003524
3525 Returns an instance of the :class:`Filter` class. If *name* is specified, it
3526 names a logger which, together with its children, will have its events allowed
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003527 through the filter. If *name* is the empty string, allows every event.
Georg Brandl116aa622007-08-15 14:28:22 +00003528
3529
Benjamin Petersone41251e2008-04-25 01:59:09 +00003530 .. method:: filter(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003531
Benjamin Petersone41251e2008-04-25 01:59:09 +00003532 Is the specified record to be logged? Returns zero for no, nonzero for
3533 yes. If deemed appropriate, the record may be modified in-place by this
3534 method.
Georg Brandl116aa622007-08-15 14:28:22 +00003535
Vinay Sajip81010212010-08-19 19:17:41 +00003536Note that filters attached to handlers are consulted whenever an event is
3537emitted by the handler, whereas filters attached to loggers are consulted
3538whenever an event is logged to the handler (using :meth:`debug`, :meth:`info`,
3539etc.) This means that events which have been generated by descendant loggers
3540will not be filtered by a logger's filter setting, unless the filter has also
3541been applied to those descendant loggers.
3542
Vinay Sajip22246fd2010-10-20 11:40:02 +00003543You don't actually need to subclass ``Filter``: you can pass any instance
3544which has a ``filter`` method with the same semantics.
3545
Vinay Sajipfc082ca2010-10-19 21:13:49 +00003546.. versionchanged:: 3.2
Vinay Sajip05ed6952010-10-20 20:34:09 +00003547 You don't need to create specialized ``Filter`` classes, or use other
3548 classes with a ``filter`` method: you can use a function (or other
3549 callable) as a filter. The filtering logic will check to see if the filter
3550 object has a ``filter`` attribute: if it does, it's assumed to be a
3551 ``Filter`` and its :meth:`~Filter.filter` method is called. Otherwise, it's
3552 assumed to be a callable and called with the record as the single
3553 parameter. The returned value should conform to that returned by
3554 :meth:`~Filter.filter`.
Vinay Sajipfc082ca2010-10-19 21:13:49 +00003555
Vinay Sajipac007992010-09-17 12:45:26 +00003556Other uses for filters
3557^^^^^^^^^^^^^^^^^^^^^^
3558
3559Although filters are used primarily to filter records based on more
3560sophisticated criteria than levels, they get to see every record which is
3561processed by the handler or logger they're attached to: this can be useful if
3562you want to do things like counting how many records were processed by a
3563particular logger or handler, or adding, changing or removing attributes in
3564the LogRecord being processed. Obviously changing the LogRecord needs to be
3565done with some care, but it does allow the injection of contextual information
3566into logs (see :ref:`filters-contextual`).
3567
Vinay Sajipd31f3632010-06-29 15:31:15 +00003568.. _log-record:
Georg Brandl116aa622007-08-15 14:28:22 +00003569
3570LogRecord Objects
3571-----------------
3572
Vinay Sajip4039aff2010-09-11 10:25:28 +00003573:class:`LogRecord` instances are created automatically by the :class:`Logger`
3574every time something is logged, and can be created manually via
3575:func:`makeLogRecord` (for example, from a pickled event received over the
3576wire).
Georg Brandl116aa622007-08-15 14:28:22 +00003577
3578
Vinay Sajipa18b9592010-12-12 13:20:55 +00003579.. class:: LogRecord(name, levelno, pathname, lineno, msg, args, exc_info, func=None, sinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003580
Vinay Sajip4039aff2010-09-11 10:25:28 +00003581 Contains all the information pertinent to the event being logged.
Georg Brandl116aa622007-08-15 14:28:22 +00003582
Vinay Sajip4039aff2010-09-11 10:25:28 +00003583 The primary information is passed in :attr:`msg` and :attr:`args`, which
3584 are combined using ``msg % args`` to create the :attr:`message` field of the
3585 record.
3586
3587 .. attribute:: args
3588
3589 Tuple of arguments to be used in formatting :attr:`msg`.
3590
3591 .. attribute:: exc_info
3592
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003593 Exception tuple (à la :func:`sys.exc_info`) or ``None`` if no exception
Georg Brandl6faee4e2010-09-21 14:48:28 +00003594 information is available.
Vinay Sajip4039aff2010-09-11 10:25:28 +00003595
3596 .. attribute:: func
3597
3598 Name of the function of origin (i.e. in which the logging call was made).
3599
3600 .. attribute:: lineno
3601
3602 Line number in the source file of origin.
3603
Vinay Sajipa18b9592010-12-12 13:20:55 +00003604 .. attribute:: levelno
Vinay Sajip4039aff2010-09-11 10:25:28 +00003605
3606 Numeric logging level.
3607
3608 .. attribute:: message
3609
3610 Bound to the result of :meth:`getMessage` when
3611 :meth:`Formatter.format(record)<Formatter.format>` is invoked.
3612
3613 .. attribute:: msg
3614
3615 User-supplied :ref:`format string<string-formatting>` or arbitrary object
3616 (see :ref:`arbitrary-object-messages`) used in :meth:`getMessage`.
3617
3618 .. attribute:: name
3619
3620 Name of the logger that emitted the record.
3621
3622 .. attribute:: pathname
3623
3624 Absolute pathname of the source file of origin.
Georg Brandl116aa622007-08-15 14:28:22 +00003625
Vinay Sajip8593ae62010-11-14 21:33:04 +00003626 .. attribute:: stack_info
3627
3628 Stack frame information (where available) from the bottom of the stack
3629 in the current thread, up to and including the stack frame of the
3630 logging call which resulted in the creation of this record.
3631
Benjamin Petersone41251e2008-04-25 01:59:09 +00003632 .. method:: getMessage()
Georg Brandl116aa622007-08-15 14:28:22 +00003633
Benjamin Petersone41251e2008-04-25 01:59:09 +00003634 Returns the message for this :class:`LogRecord` instance after merging any
Vinay Sajip4039aff2010-09-11 10:25:28 +00003635 user-supplied arguments with the message. If the user-supplied message
3636 argument to the logging call is not a string, :func:`str` is called on it to
3637 convert it to a string. This allows use of user-defined classes as
3638 messages, whose ``__str__`` method can return the actual format string to
3639 be used.
3640
Vinay Sajip61561522010-12-03 11:50:38 +00003641 .. versionchanged:: 3.2
3642 The creation of a ``LogRecord`` has been made more configurable by
3643 providing a factory which is used to create the record. The factory can be
3644 set using :func:`getLogRecordFactory` and :func:`setLogRecordFactory`
3645 (see this for the factory's signature).
3646
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003647 This functionality can be used to inject your own values into a
3648 LogRecord at creation time. You can use the following pattern::
Vinay Sajip61561522010-12-03 11:50:38 +00003649
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003650 old_factory = logging.getLogRecordFactory()
Vinay Sajip61561522010-12-03 11:50:38 +00003651
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003652 def record_factory(*args, **kwargs):
3653 record = old_factory(*args, **kwargs)
3654 record.custom_attribute = 0xdecafbad
3655 return record
Vinay Sajip61561522010-12-03 11:50:38 +00003656
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003657 logging.setLogRecordFactory(record_factory)
Vinay Sajip61561522010-12-03 11:50:38 +00003658
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003659 With this pattern, multiple factories could be chained, and as long
3660 as they don't overwrite each other's attributes or unintentionally
3661 overwrite the standard attributes listed above, there should be no
3662 surprises.
3663
Vinay Sajip61561522010-12-03 11:50:38 +00003664
Vinay Sajipd31f3632010-06-29 15:31:15 +00003665.. _logger-adapter:
Georg Brandl116aa622007-08-15 14:28:22 +00003666
Christian Heimes04c420f2008-01-18 18:40:46 +00003667LoggerAdapter Objects
3668---------------------
3669
Christian Heimes04c420f2008-01-18 18:40:46 +00003670:class:`LoggerAdapter` instances are used to conveniently pass contextual
Georg Brandl86def6c2008-01-21 20:36:10 +00003671information into logging calls. For a usage example , see the section on
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003672:ref:`adding contextual information to your logging output <context-info>`.
Georg Brandl86def6c2008-01-21 20:36:10 +00003673
Christian Heimes04c420f2008-01-18 18:40:46 +00003674
3675.. class:: LoggerAdapter(logger, extra)
3676
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003677 Returns an instance of :class:`LoggerAdapter` initialized with an
3678 underlying :class:`Logger` instance and a dict-like object.
Christian Heimes04c420f2008-01-18 18:40:46 +00003679
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003680 .. method:: process(msg, kwargs)
Christian Heimes04c420f2008-01-18 18:40:46 +00003681
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003682 Modifies the message and/or keyword arguments passed to a logging call in
3683 order to insert contextual information. This implementation takes the object
3684 passed as *extra* to the constructor and adds it to *kwargs* using key
3685 'extra'. The return value is a (*msg*, *kwargs*) tuple which has the
3686 (possibly modified) versions of the arguments passed in.
Christian Heimes04c420f2008-01-18 18:40:46 +00003687
Vinay Sajipc84f0162010-09-21 11:25:39 +00003688In addition to the above, :class:`LoggerAdapter` supports the following
Christian Heimes04c420f2008-01-18 18:40:46 +00003689methods of :class:`Logger`, i.e. :meth:`debug`, :meth:`info`, :meth:`warning`,
Vinay Sajipc84f0162010-09-21 11:25:39 +00003690:meth:`error`, :meth:`exception`, :meth:`critical`, :meth:`log`,
3691:meth:`isEnabledFor`, :meth:`getEffectiveLevel`, :meth:`setLevel`,
3692:meth:`hasHandlers`. These methods have the same signatures as their
3693counterparts in :class:`Logger`, so you can use the two types of instances
3694interchangeably.
Christian Heimes04c420f2008-01-18 18:40:46 +00003695
Ezio Melotti4d5195b2010-04-20 10:57:44 +00003696.. versionchanged:: 3.2
Vinay Sajipc84f0162010-09-21 11:25:39 +00003697 The :meth:`isEnabledFor`, :meth:`getEffectiveLevel`, :meth:`setLevel` and
3698 :meth:`hasHandlers` methods were added to :class:`LoggerAdapter`. These
3699 methods delegate to the underlying logger.
Benjamin Peterson22005fc2010-04-11 16:25:06 +00003700
Georg Brandl116aa622007-08-15 14:28:22 +00003701
3702Thread Safety
3703-------------
3704
3705The logging module is intended to be thread-safe without any special work
3706needing to be done by its clients. It achieves this though using threading
3707locks; there is one lock to serialize access to the module's shared data, and
3708each handler also creates a lock to serialize access to its underlying I/O.
3709
Benjamin Petersond23f8222009-04-05 19:13:16 +00003710If you are implementing asynchronous signal handlers using the :mod:`signal`
3711module, you may not be able to use logging from within such handlers. This is
3712because lock implementations in the :mod:`threading` module are not always
3713re-entrant, and so cannot be invoked from such signal handlers.
Georg Brandl116aa622007-08-15 14:28:22 +00003714
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00003715
3716Integration with the warnings module
3717------------------------------------
3718
3719The :func:`captureWarnings` function can be used to integrate :mod:`logging`
3720with the :mod:`warnings` module.
3721
3722.. function:: captureWarnings(capture)
3723
3724 This function is used to turn the capture of warnings by logging on and
3725 off.
3726
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003727 If *capture* is ``True``, warnings issued by the :mod:`warnings` module will
3728 be redirected to the logging system. Specifically, a warning will be
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00003729 formatted using :func:`warnings.formatwarning` and the resulting string
3730 logged to a logger named "py.warnings" with a severity of `WARNING`.
3731
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003732 If *capture* is ``False``, the redirection of warnings to the logging system
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00003733 will stop, and warnings will be redirected to their original destinations
3734 (i.e. those in effect before `captureWarnings(True)` was called).
3735
3736
Georg Brandl116aa622007-08-15 14:28:22 +00003737Configuration
3738-------------
3739
3740
3741.. _logging-config-api:
3742
3743Configuration functions
3744^^^^^^^^^^^^^^^^^^^^^^^
3745
Georg Brandl116aa622007-08-15 14:28:22 +00003746The following functions configure the logging module. They are located in the
3747:mod:`logging.config` module. Their use is optional --- you can configure the
3748logging module using these functions or by making calls to the main API (defined
3749in :mod:`logging` itself) and defining handlers which are declared either in
3750:mod:`logging` or :mod:`logging.handlers`.
3751
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003752.. function:: dictConfig(config)
Georg Brandl116aa622007-08-15 14:28:22 +00003753
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003754 Takes the logging configuration from a dictionary. The contents of
3755 this dictionary are described in :ref:`logging-config-dictschema`
3756 below.
3757
3758 If an error is encountered during configuration, this function will
3759 raise a :exc:`ValueError`, :exc:`TypeError`, :exc:`AttributeError`
3760 or :exc:`ImportError` with a suitably descriptive message. The
3761 following is a (possibly incomplete) list of conditions which will
3762 raise an error:
3763
3764 * A ``level`` which is not a string or which is a string not
3765 corresponding to an actual logging level.
3766 * A ``propagate`` value which is not a boolean.
3767 * An id which does not have a corresponding destination.
3768 * A non-existent handler id found during an incremental call.
3769 * An invalid logger name.
3770 * Inability to resolve to an internal or external object.
3771
3772 Parsing is performed by the :class:`DictConfigurator` class, whose
3773 constructor is passed the dictionary used for configuration, and
3774 has a :meth:`configure` method. The :mod:`logging.config` module
3775 has a callable attribute :attr:`dictConfigClass`
3776 which is initially set to :class:`DictConfigurator`.
3777 You can replace the value of :attr:`dictConfigClass` with a
3778 suitable implementation of your own.
3779
3780 :func:`dictConfig` calls :attr:`dictConfigClass` passing
3781 the specified dictionary, and then calls the :meth:`configure` method on
3782 the returned object to put the configuration into effect::
3783
3784 def dictConfig(config):
3785 dictConfigClass(config).configure()
3786
3787 For example, a subclass of :class:`DictConfigurator` could call
3788 ``DictConfigurator.__init__()`` in its own :meth:`__init__()`, then
3789 set up custom prefixes which would be usable in the subsequent
3790 :meth:`configure` call. :attr:`dictConfigClass` would be bound to
3791 this new subclass, and then :func:`dictConfig` could be called exactly as
3792 in the default, uncustomized state.
3793
3794.. function:: fileConfig(fname[, defaults])
Georg Brandl116aa622007-08-15 14:28:22 +00003795
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00003796 Reads the logging configuration from a :mod:`configparser`\-format file named
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00003797 *fname*. This function can be called several times from an application,
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003798 allowing an end user to select from various pre-canned
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00003799 configurations (if the developer provides a mechanism to present the choices
3800 and load the chosen configuration). Defaults to be passed to the ConfigParser
3801 can be specified in the *defaults* argument.
Georg Brandl116aa622007-08-15 14:28:22 +00003802
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003803
3804.. function:: listen(port=DEFAULT_LOGGING_CONFIG_PORT)
Georg Brandl116aa622007-08-15 14:28:22 +00003805
3806 Starts up a socket server on the specified port, and listens for new
3807 configurations. If no port is specified, the module's default
3808 :const:`DEFAULT_LOGGING_CONFIG_PORT` is used. Logging configurations will be
3809 sent as a file suitable for processing by :func:`fileConfig`. Returns a
3810 :class:`Thread` instance on which you can call :meth:`start` to start the
3811 server, and which you can :meth:`join` when appropriate. To stop the server,
Christian Heimes8b0facf2007-12-04 19:30:01 +00003812 call :func:`stopListening`.
3813
3814 To send a configuration to the socket, read in the configuration file and
3815 send it to the socket as a string of bytes preceded by a four-byte length
3816 string packed in binary using ``struct.pack('>L', n)``.
Georg Brandl116aa622007-08-15 14:28:22 +00003817
3818
3819.. function:: stopListening()
3820
Christian Heimes8b0facf2007-12-04 19:30:01 +00003821 Stops the listening server which was created with a call to :func:`listen`.
3822 This is typically called before calling :meth:`join` on the return value from
Georg Brandl116aa622007-08-15 14:28:22 +00003823 :func:`listen`.
3824
3825
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003826.. _logging-config-dictschema:
3827
3828Configuration dictionary schema
3829^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3830
3831Describing a logging configuration requires listing the various
3832objects to create and the connections between them; for example, you
3833may create a handler named "console" and then say that the logger
3834named "startup" will send its messages to the "console" handler.
3835These objects aren't limited to those provided by the :mod:`logging`
3836module because you might write your own formatter or handler class.
3837The parameters to these classes may also need to include external
3838objects such as ``sys.stderr``. The syntax for describing these
3839objects and connections is defined in :ref:`logging-config-dict-connections`
3840below.
3841
3842Dictionary Schema Details
3843"""""""""""""""""""""""""
3844
3845The dictionary passed to :func:`dictConfig` must contain the following
3846keys:
3847
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003848* *version* - to be set to an integer value representing the schema
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003849 version. The only valid value at present is 1, but having this key
3850 allows the schema to evolve while still preserving backwards
3851 compatibility.
3852
3853All other keys are optional, but if present they will be interpreted
3854as described below. In all cases below where a 'configuring dict' is
3855mentioned, it will be checked for the special ``'()'`` key to see if a
3856custom instantiation is required. If so, the mechanism described in
3857:ref:`logging-config-dict-userdef` below is used to create an instance;
3858otherwise, the context is used to determine what to instantiate.
3859
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003860* *formatters* - the corresponding value will be a dict in which each
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003861 key is a formatter id and each value is a dict describing how to
3862 configure the corresponding Formatter instance.
3863
3864 The configuring dict is searched for keys ``format`` and ``datefmt``
3865 (with defaults of ``None``) and these are used to construct a
3866 :class:`logging.Formatter` instance.
3867
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003868* *filters* - the corresponding value will be a dict in which each key
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003869 is a filter id and each value is a dict describing how to configure
3870 the corresponding Filter instance.
3871
3872 The configuring dict is searched for the key ``name`` (defaulting to the
3873 empty string) and this is used to construct a :class:`logging.Filter`
3874 instance.
3875
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003876* *handlers* - the corresponding value will be a dict in which each
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003877 key is a handler id and each value is a dict describing how to
3878 configure the corresponding Handler instance.
3879
3880 The configuring dict is searched for the following keys:
3881
3882 * ``class`` (mandatory). This is the fully qualified name of the
3883 handler class.
3884
3885 * ``level`` (optional). The level of the handler.
3886
3887 * ``formatter`` (optional). The id of the formatter for this
3888 handler.
3889
3890 * ``filters`` (optional). A list of ids of the filters for this
3891 handler.
3892
3893 All *other* keys are passed through as keyword arguments to the
3894 handler's constructor. For example, given the snippet::
3895
3896 handlers:
3897 console:
3898 class : logging.StreamHandler
3899 formatter: brief
3900 level : INFO
3901 filters: [allow_foo]
3902 stream : ext://sys.stdout
3903 file:
3904 class : logging.handlers.RotatingFileHandler
3905 formatter: precise
3906 filename: logconfig.log
3907 maxBytes: 1024
3908 backupCount: 3
3909
3910 the handler with id ``console`` is instantiated as a
3911 :class:`logging.StreamHandler`, using ``sys.stdout`` as the underlying
3912 stream. The handler with id ``file`` is instantiated as a
3913 :class:`logging.handlers.RotatingFileHandler` with the keyword arguments
3914 ``filename='logconfig.log', maxBytes=1024, backupCount=3``.
3915
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003916* *loggers* - the corresponding value will be a dict in which each key
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003917 is a logger name and each value is a dict describing how to
3918 configure the corresponding Logger instance.
3919
3920 The configuring dict is searched for the following keys:
3921
3922 * ``level`` (optional). The level of the logger.
3923
3924 * ``propagate`` (optional). The propagation setting of the logger.
3925
3926 * ``filters`` (optional). A list of ids of the filters for this
3927 logger.
3928
3929 * ``handlers`` (optional). A list of ids of the handlers for this
3930 logger.
3931
3932 The specified loggers will be configured according to the level,
3933 propagation, filters and handlers specified.
3934
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003935* *root* - this will be the configuration for the root logger.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003936 Processing of the configuration will be as for any logger, except
3937 that the ``propagate`` setting will not be applicable.
3938
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003939* *incremental* - whether the configuration is to be interpreted as
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003940 incremental to the existing configuration. This value defaults to
3941 ``False``, which means that the specified configuration replaces the
3942 existing configuration with the same semantics as used by the
3943 existing :func:`fileConfig` API.
3944
3945 If the specified value is ``True``, the configuration is processed
3946 as described in the section on :ref:`logging-config-dict-incremental`.
3947
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003948* *disable_existing_loggers* - whether any existing loggers are to be
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003949 disabled. This setting mirrors the parameter of the same name in
3950 :func:`fileConfig`. If absent, this parameter defaults to ``True``.
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003951 This value is ignored if *incremental* is ``True``.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003952
3953.. _logging-config-dict-incremental:
3954
3955Incremental Configuration
3956"""""""""""""""""""""""""
3957
3958It is difficult to provide complete flexibility for incremental
3959configuration. For example, because objects such as filters
3960and formatters are anonymous, once a configuration is set up, it is
3961not possible to refer to such anonymous objects when augmenting a
3962configuration.
3963
3964Furthermore, there is not a compelling case for arbitrarily altering
3965the object graph of loggers, handlers, filters, formatters at
3966run-time, once a configuration is set up; the verbosity of loggers and
3967handlers can be controlled just by setting levels (and, in the case of
3968loggers, propagation flags). Changing the object graph arbitrarily in
3969a safe way is problematic in a multi-threaded environment; while not
3970impossible, the benefits are not worth the complexity it adds to the
3971implementation.
3972
3973Thus, when the ``incremental`` key of a configuration dict is present
3974and is ``True``, the system will completely ignore any ``formatters`` and
3975``filters`` entries, and process only the ``level``
3976settings in the ``handlers`` entries, and the ``level`` and
3977``propagate`` settings in the ``loggers`` and ``root`` entries.
3978
3979Using a value in the configuration dict lets configurations to be sent
3980over the wire as pickled dicts to a socket listener. Thus, the logging
3981verbosity of a long-running application can be altered over time with
3982no need to stop and restart the application.
3983
3984.. _logging-config-dict-connections:
3985
3986Object connections
3987""""""""""""""""""
3988
3989The schema describes a set of logging objects - loggers,
3990handlers, formatters, filters - which are connected to each other in
3991an object graph. Thus, the schema needs to represent connections
3992between the objects. For example, say that, once configured, a
3993particular logger has attached to it a particular handler. For the
3994purposes of this discussion, we can say that the logger represents the
3995source, and the handler the destination, of a connection between the
3996two. Of course in the configured objects this is represented by the
3997logger holding a reference to the handler. In the configuration dict,
3998this is done by giving each destination object an id which identifies
3999it unambiguously, and then using the id in the source object's
4000configuration to indicate that a connection exists between the source
4001and the destination object with that id.
4002
4003So, for example, consider the following YAML snippet::
4004
4005 formatters:
4006 brief:
4007 # configuration for formatter with id 'brief' goes here
4008 precise:
4009 # configuration for formatter with id 'precise' goes here
4010 handlers:
4011 h1: #This is an id
4012 # configuration of handler with id 'h1' goes here
4013 formatter: brief
4014 h2: #This is another id
4015 # configuration of handler with id 'h2' goes here
4016 formatter: precise
4017 loggers:
4018 foo.bar.baz:
4019 # other configuration for logger 'foo.bar.baz'
4020 handlers: [h1, h2]
4021
4022(Note: YAML used here because it's a little more readable than the
4023equivalent Python source form for the dictionary.)
4024
4025The ids for loggers are the logger names which would be used
4026programmatically to obtain a reference to those loggers, e.g.
4027``foo.bar.baz``. The ids for Formatters and Filters can be any string
4028value (such as ``brief``, ``precise`` above) and they are transient,
4029in that they are only meaningful for processing the configuration
4030dictionary and used to determine connections between objects, and are
4031not persisted anywhere when the configuration call is complete.
4032
4033The above snippet indicates that logger named ``foo.bar.baz`` should
4034have two handlers attached to it, which are described by the handler
4035ids ``h1`` and ``h2``. The formatter for ``h1`` is that described by id
4036``brief``, and the formatter for ``h2`` is that described by id
4037``precise``.
4038
4039
4040.. _logging-config-dict-userdef:
4041
4042User-defined objects
4043""""""""""""""""""""
4044
4045The schema supports user-defined objects for handlers, filters and
4046formatters. (Loggers do not need to have different types for
4047different instances, so there is no support in this configuration
4048schema for user-defined logger classes.)
4049
4050Objects to be configured are described by dictionaries
4051which detail their configuration. In some places, the logging system
4052will be able to infer from the context how an object is to be
4053instantiated, but when a user-defined object is to be instantiated,
4054the system will not know how to do this. In order to provide complete
4055flexibility for user-defined object instantiation, the user needs
4056to provide a 'factory' - a callable which is called with a
4057configuration dictionary and which returns the instantiated object.
4058This is signalled by an absolute import path to the factory being
4059made available under the special key ``'()'``. Here's a concrete
4060example::
4061
4062 formatters:
4063 brief:
4064 format: '%(message)s'
4065 default:
4066 format: '%(asctime)s %(levelname)-8s %(name)-15s %(message)s'
4067 datefmt: '%Y-%m-%d %H:%M:%S'
4068 custom:
4069 (): my.package.customFormatterFactory
4070 bar: baz
4071 spam: 99.9
4072 answer: 42
4073
4074The above YAML snippet defines three formatters. The first, with id
4075``brief``, is a standard :class:`logging.Formatter` instance with the
4076specified format string. The second, with id ``default``, has a
4077longer format and also defines the time format explicitly, and will
4078result in a :class:`logging.Formatter` initialized with those two format
4079strings. Shown in Python source form, the ``brief`` and ``default``
4080formatters have configuration sub-dictionaries::
4081
4082 {
4083 'format' : '%(message)s'
4084 }
4085
4086and::
4087
4088 {
4089 'format' : '%(asctime)s %(levelname)-8s %(name)-15s %(message)s',
4090 'datefmt' : '%Y-%m-%d %H:%M:%S'
4091 }
4092
4093respectively, and as these dictionaries do not contain the special key
4094``'()'``, the instantiation is inferred from the context: as a result,
4095standard :class:`logging.Formatter` instances are created. The
4096configuration sub-dictionary for the third formatter, with id
4097``custom``, is::
4098
4099 {
4100 '()' : 'my.package.customFormatterFactory',
4101 'bar' : 'baz',
4102 'spam' : 99.9,
4103 'answer' : 42
4104 }
4105
4106and this contains the special key ``'()'``, which means that
4107user-defined instantiation is wanted. In this case, the specified
4108factory callable will be used. If it is an actual callable it will be
4109used directly - otherwise, if you specify a string (as in the example)
4110the actual callable will be located using normal import mechanisms.
4111The callable will be called with the **remaining** items in the
4112configuration sub-dictionary as keyword arguments. In the above
4113example, the formatter with id ``custom`` will be assumed to be
4114returned by the call::
4115
4116 my.package.customFormatterFactory(bar='baz', spam=99.9, answer=42)
4117
4118The key ``'()'`` has been used as the special key because it is not a
4119valid keyword parameter name, and so will not clash with the names of
4120the keyword arguments used in the call. The ``'()'`` also serves as a
4121mnemonic that the corresponding value is a callable.
4122
4123
4124.. _logging-config-dict-externalobj:
4125
4126Access to external objects
4127""""""""""""""""""""""""""
4128
4129There are times where a configuration needs to refer to objects
4130external to the configuration, for example ``sys.stderr``. If the
4131configuration dict is constructed using Python code, this is
4132straightforward, but a problem arises when the configuration is
4133provided via a text file (e.g. JSON, YAML). In a text file, there is
4134no standard way to distinguish ``sys.stderr`` from the literal string
4135``'sys.stderr'``. To facilitate this distinction, the configuration
4136system looks for certain special prefixes in string values and
4137treat them specially. For example, if the literal string
4138``'ext://sys.stderr'`` is provided as a value in the configuration,
4139then the ``ext://`` will be stripped off and the remainder of the
4140value processed using normal import mechanisms.
4141
4142The handling of such prefixes is done in a way analogous to protocol
4143handling: there is a generic mechanism to look for prefixes which
4144match the regular expression ``^(?P<prefix>[a-z]+)://(?P<suffix>.*)$``
4145whereby, if the ``prefix`` is recognised, the ``suffix`` is processed
4146in a prefix-dependent manner and the result of the processing replaces
4147the string value. If the prefix is not recognised, then the string
4148value will be left as-is.
4149
4150
4151.. _logging-config-dict-internalobj:
4152
4153Access to internal objects
4154""""""""""""""""""""""""""
4155
4156As well as external objects, there is sometimes also a need to refer
4157to objects in the configuration. This will be done implicitly by the
4158configuration system for things that it knows about. For example, the
4159string value ``'DEBUG'`` for a ``level`` in a logger or handler will
4160automatically be converted to the value ``logging.DEBUG``, and the
4161``handlers``, ``filters`` and ``formatter`` entries will take an
4162object id and resolve to the appropriate destination object.
4163
4164However, a more generic mechanism is needed for user-defined
4165objects which are not known to the :mod:`logging` module. For
4166example, consider :class:`logging.handlers.MemoryHandler`, which takes
4167a ``target`` argument which is another handler to delegate to. Since
4168the system already knows about this class, then in the configuration,
4169the given ``target`` just needs to be the object id of the relevant
4170target handler, and the system will resolve to the handler from the
4171id. If, however, a user defines a ``my.package.MyHandler`` which has
4172an ``alternate`` handler, the configuration system would not know that
4173the ``alternate`` referred to a handler. To cater for this, a generic
4174resolution system allows the user to specify::
4175
4176 handlers:
4177 file:
4178 # configuration of file handler goes here
4179
4180 custom:
4181 (): my.package.MyHandler
4182 alternate: cfg://handlers.file
4183
4184The literal string ``'cfg://handlers.file'`` will be resolved in an
4185analogous way to strings with the ``ext://`` prefix, but looking
4186in the configuration itself rather than the import namespace. The
4187mechanism allows access by dot or by index, in a similar way to
4188that provided by ``str.format``. Thus, given the following snippet::
4189
4190 handlers:
4191 email:
4192 class: logging.handlers.SMTPHandler
4193 mailhost: localhost
4194 fromaddr: my_app@domain.tld
4195 toaddrs:
4196 - support_team@domain.tld
4197 - dev_team@domain.tld
4198 subject: Houston, we have a problem.
4199
4200in the configuration, the string ``'cfg://handlers'`` would resolve to
4201the dict with key ``handlers``, the string ``'cfg://handlers.email``
4202would resolve to the dict with key ``email`` in the ``handlers`` dict,
4203and so on. The string ``'cfg://handlers.email.toaddrs[1]`` would
4204resolve to ``'dev_team.domain.tld'`` and the string
4205``'cfg://handlers.email.toaddrs[0]'`` would resolve to the value
4206``'support_team@domain.tld'``. The ``subject`` value could be accessed
4207using either ``'cfg://handlers.email.subject'`` or, equivalently,
4208``'cfg://handlers.email[subject]'``. The latter form only needs to be
4209used if the key contains spaces or non-alphanumeric characters. If an
4210index value consists only of decimal digits, access will be attempted
4211using the corresponding integer value, falling back to the string
4212value if needed.
4213
4214Given a string ``cfg://handlers.myhandler.mykey.123``, this will
4215resolve to ``config_dict['handlers']['myhandler']['mykey']['123']``.
4216If the string is specified as ``cfg://handlers.myhandler.mykey[123]``,
4217the system will attempt to retrieve the value from
4218``config_dict['handlers']['myhandler']['mykey'][123]``, and fall back
4219to ``config_dict['handlers']['myhandler']['mykey']['123']`` if that
4220fails.
4221
Georg Brandl116aa622007-08-15 14:28:22 +00004222.. _logging-config-fileformat:
4223
4224Configuration file format
4225^^^^^^^^^^^^^^^^^^^^^^^^^
4226
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00004227The configuration file format understood by :func:`fileConfig` is based on
4228:mod:`configparser` functionality. The file must contain sections called
4229``[loggers]``, ``[handlers]`` and ``[formatters]`` which identify by name the
4230entities of each type which are defined in the file. For each such entity, there
4231is a separate section which identifies how that entity is configured. Thus, for
4232a logger named ``log01`` in the ``[loggers]`` section, the relevant
4233configuration details are held in a section ``[logger_log01]``. Similarly, a
4234handler called ``hand01`` in the ``[handlers]`` section will have its
4235configuration held in a section called ``[handler_hand01]``, while a formatter
4236called ``form01`` in the ``[formatters]`` section will have its configuration
4237specified in a section called ``[formatter_form01]``. The root logger
4238configuration must be specified in a section called ``[logger_root]``.
Georg Brandl116aa622007-08-15 14:28:22 +00004239
4240Examples of these sections in the file are given below. ::
4241
4242 [loggers]
4243 keys=root,log02,log03,log04,log05,log06,log07
4244
4245 [handlers]
4246 keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
4247
4248 [formatters]
4249 keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
4250
4251The root logger must specify a level and a list of handlers. An example of a
4252root logger section is given below. ::
4253
4254 [logger_root]
4255 level=NOTSET
4256 handlers=hand01
4257
4258The ``level`` entry can be one of ``DEBUG, INFO, WARNING, ERROR, CRITICAL`` or
4259``NOTSET``. For the root logger only, ``NOTSET`` means that all messages will be
4260logged. Level values are :func:`eval`\ uated in the context of the ``logging``
4261package's namespace.
4262
4263The ``handlers`` entry is a comma-separated list of handler names, which must
4264appear in the ``[handlers]`` section. These names must appear in the
4265``[handlers]`` section and have corresponding sections in the configuration
4266file.
4267
4268For loggers other than the root logger, some additional information is required.
4269This is illustrated by the following example. ::
4270
4271 [logger_parser]
4272 level=DEBUG
4273 handlers=hand01
4274 propagate=1
4275 qualname=compiler.parser
4276
4277The ``level`` and ``handlers`` entries are interpreted as for the root logger,
4278except that if a non-root logger's level is specified as ``NOTSET``, the system
4279consults loggers higher up the hierarchy to determine the effective level of the
4280logger. The ``propagate`` entry is set to 1 to indicate that messages must
4281propagate to handlers higher up the logger hierarchy from this logger, or 0 to
4282indicate that messages are **not** propagated to handlers up the hierarchy. The
4283``qualname`` entry is the hierarchical channel name of the logger, that is to
4284say the name used by the application to get the logger.
4285
4286Sections which specify handler configuration are exemplified by the following.
4287::
4288
4289 [handler_hand01]
4290 class=StreamHandler
4291 level=NOTSET
4292 formatter=form01
4293 args=(sys.stdout,)
4294
4295The ``class`` entry indicates the handler's class (as determined by :func:`eval`
4296in the ``logging`` package's namespace). The ``level`` is interpreted as for
4297loggers, and ``NOTSET`` is taken to mean "log everything".
4298
4299The ``formatter`` entry indicates the key name of the formatter for this
4300handler. If blank, a default formatter (``logging._defaultFormatter``) is used.
4301If a name is specified, it must appear in the ``[formatters]`` section and have
4302a corresponding section in the configuration file.
4303
4304The ``args`` entry, when :func:`eval`\ uated in the context of the ``logging``
4305package's namespace, is the list of arguments to the constructor for the handler
4306class. Refer to the constructors for the relevant handlers, or to the examples
4307below, to see how typical entries are constructed. ::
4308
4309 [handler_hand02]
4310 class=FileHandler
4311 level=DEBUG
4312 formatter=form02
4313 args=('python.log', 'w')
4314
4315 [handler_hand03]
4316 class=handlers.SocketHandler
4317 level=INFO
4318 formatter=form03
4319 args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
4320
4321 [handler_hand04]
4322 class=handlers.DatagramHandler
4323 level=WARN
4324 formatter=form04
4325 args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
4326
4327 [handler_hand05]
4328 class=handlers.SysLogHandler
4329 level=ERROR
4330 formatter=form05
4331 args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
4332
4333 [handler_hand06]
4334 class=handlers.NTEventLogHandler
4335 level=CRITICAL
4336 formatter=form06
4337 args=('Python Application', '', 'Application')
4338
4339 [handler_hand07]
4340 class=handlers.SMTPHandler
4341 level=WARN
4342 formatter=form07
4343 args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
4344
4345 [handler_hand08]
4346 class=handlers.MemoryHandler
4347 level=NOTSET
4348 formatter=form08
4349 target=
4350 args=(10, ERROR)
4351
4352 [handler_hand09]
4353 class=handlers.HTTPHandler
4354 level=NOTSET
4355 formatter=form09
4356 args=('localhost:9022', '/log', 'GET')
4357
4358Sections which specify formatter configuration are typified by the following. ::
4359
4360 [formatter_form01]
4361 format=F1 %(asctime)s %(levelname)s %(message)s
4362 datefmt=
4363 class=logging.Formatter
4364
4365The ``format`` entry is the overall format string, and the ``datefmt`` entry is
Christian Heimes5b5e81c2007-12-31 16:14:33 +00004366the :func:`strftime`\ -compatible date/time format string. If empty, the
4367package substitutes ISO8601 format date/times, which is almost equivalent to
4368specifying the date format string ``"%Y-%m-%d %H:%M:%S"``. The ISO8601 format
4369also specifies milliseconds, which are appended to the result of using the above
4370format string, with a comma separator. An example time in ISO8601 format is
4371``2003-01-23 00:29:50,411``.
Georg Brandl116aa622007-08-15 14:28:22 +00004372
4373The ``class`` entry is optional. It indicates the name of the formatter's class
4374(as a dotted module and class name.) This option is useful for instantiating a
4375:class:`Formatter` subclass. Subclasses of :class:`Formatter` can present
4376exception tracebacks in an expanded or condensed format.
4377
Christian Heimes8b0facf2007-12-04 19:30:01 +00004378
4379Configuration server example
4380^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4381
4382Here is an example of a module using the logging configuration server::
4383
4384 import logging
4385 import logging.config
4386 import time
4387 import os
4388
4389 # read initial config file
4390 logging.config.fileConfig("logging.conf")
4391
4392 # create and start listener on port 9999
4393 t = logging.config.listen(9999)
4394 t.start()
4395
4396 logger = logging.getLogger("simpleExample")
4397
4398 try:
4399 # loop through logging calls to see the difference
4400 # new configurations make, until Ctrl+C is pressed
4401 while True:
4402 logger.debug("debug message")
4403 logger.info("info message")
4404 logger.warn("warn message")
4405 logger.error("error message")
4406 logger.critical("critical message")
4407 time.sleep(5)
4408 except KeyboardInterrupt:
4409 # cleanup
4410 logging.config.stopListening()
4411 t.join()
4412
4413And here is a script that takes a filename and sends that file to the server,
4414properly preceded with the binary-encoded length, as the new logging
4415configuration::
4416
4417 #!/usr/bin/env python
4418 import socket, sys, struct
4419
4420 data_to_send = open(sys.argv[1], "r").read()
4421
4422 HOST = 'localhost'
4423 PORT = 9999
4424 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Georg Brandlf6945182008-02-01 11:56:49 +00004425 print("connecting...")
Christian Heimes8b0facf2007-12-04 19:30:01 +00004426 s.connect((HOST, PORT))
Georg Brandlf6945182008-02-01 11:56:49 +00004427 print("sending config...")
Christian Heimes8b0facf2007-12-04 19:30:01 +00004428 s.send(struct.pack(">L", len(data_to_send)))
4429 s.send(data_to_send)
4430 s.close()
Georg Brandlf6945182008-02-01 11:56:49 +00004431 print("complete")
Christian Heimes8b0facf2007-12-04 19:30:01 +00004432
4433
4434More examples
4435-------------
4436
4437Multiple handlers and formatters
4438^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4439
4440Loggers are plain Python objects. The :func:`addHandler` method has no minimum
4441or maximum quota for the number of handlers you may add. Sometimes it will be
4442beneficial for an application to log all messages of all severities to a text
4443file while simultaneously logging errors or above to the console. To set this
4444up, simply configure the appropriate handlers. The logging calls in the
4445application code will remain unchanged. Here is a slight modification to the
4446previous simple module-based configuration example::
4447
4448 import logging
4449
4450 logger = logging.getLogger("simple_example")
4451 logger.setLevel(logging.DEBUG)
4452 # create file handler which logs even debug messages
4453 fh = logging.FileHandler("spam.log")
4454 fh.setLevel(logging.DEBUG)
4455 # create console handler with a higher log level
4456 ch = logging.StreamHandler()
4457 ch.setLevel(logging.ERROR)
4458 # create formatter and add it to the handlers
4459 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
4460 ch.setFormatter(formatter)
4461 fh.setFormatter(formatter)
4462 # add the handlers to logger
4463 logger.addHandler(ch)
4464 logger.addHandler(fh)
4465
4466 # "application" code
4467 logger.debug("debug message")
4468 logger.info("info message")
4469 logger.warn("warn message")
4470 logger.error("error message")
4471 logger.critical("critical message")
4472
4473Notice that the "application" code does not care about multiple handlers. All
4474that changed was the addition and configuration of a new handler named *fh*.
4475
4476The ability to create new handlers with higher- or lower-severity filters can be
4477very helpful when writing and testing an application. Instead of using many
4478``print`` statements for debugging, use ``logger.debug``: Unlike the print
4479statements, which you will have to delete or comment out later, the logger.debug
4480statements can remain intact in the source code and remain dormant until you
4481need them again. At that time, the only change that needs to happen is to
4482modify the severity level of the logger and/or handler to debug.
4483
4484
4485Using logging in multiple modules
4486^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4487
4488It was mentioned above that multiple calls to
4489``logging.getLogger('someLogger')`` return a reference to the same logger
4490object. This is true not only within the same module, but also across modules
4491as long as it is in the same Python interpreter process. It is true for
4492references to the same object; additionally, application code can define and
4493configure a parent logger in one module and create (but not configure) a child
4494logger in a separate module, and all logger calls to the child will pass up to
4495the parent. Here is a main module::
4496
4497 import logging
4498 import auxiliary_module
4499
4500 # create logger with "spam_application"
4501 logger = logging.getLogger("spam_application")
4502 logger.setLevel(logging.DEBUG)
4503 # create file handler which logs even debug messages
4504 fh = logging.FileHandler("spam.log")
4505 fh.setLevel(logging.DEBUG)
4506 # create console handler with a higher log level
4507 ch = logging.StreamHandler()
4508 ch.setLevel(logging.ERROR)
4509 # create formatter and add it to the handlers
4510 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
4511 fh.setFormatter(formatter)
4512 ch.setFormatter(formatter)
4513 # add the handlers to the logger
4514 logger.addHandler(fh)
4515 logger.addHandler(ch)
4516
4517 logger.info("creating an instance of auxiliary_module.Auxiliary")
4518 a = auxiliary_module.Auxiliary()
4519 logger.info("created an instance of auxiliary_module.Auxiliary")
4520 logger.info("calling auxiliary_module.Auxiliary.do_something")
4521 a.do_something()
4522 logger.info("finished auxiliary_module.Auxiliary.do_something")
4523 logger.info("calling auxiliary_module.some_function()")
4524 auxiliary_module.some_function()
4525 logger.info("done with auxiliary_module.some_function()")
4526
4527Here is the auxiliary module::
4528
4529 import logging
4530
4531 # create logger
4532 module_logger = logging.getLogger("spam_application.auxiliary")
4533
4534 class Auxiliary:
4535 def __init__(self):
4536 self.logger = logging.getLogger("spam_application.auxiliary.Auxiliary")
4537 self.logger.info("creating an instance of Auxiliary")
4538 def do_something(self):
4539 self.logger.info("doing something")
4540 a = 1 + 1
4541 self.logger.info("done doing something")
4542
4543 def some_function():
4544 module_logger.info("received a call to \"some_function\"")
4545
4546The output looks like this::
4547
Christian Heimes043d6f62008-01-07 17:19:16 +00004548 2005-03-23 23:47:11,663 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004549 creating an instance of auxiliary_module.Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00004550 2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004551 creating an instance of Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00004552 2005-03-23 23:47:11,665 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004553 created an instance of auxiliary_module.Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00004554 2005-03-23 23:47:11,668 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004555 calling auxiliary_module.Auxiliary.do_something
Christian Heimes043d6f62008-01-07 17:19:16 +00004556 2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004557 doing something
Christian Heimes043d6f62008-01-07 17:19:16 +00004558 2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004559 done doing something
Christian Heimes043d6f62008-01-07 17:19:16 +00004560 2005-03-23 23:47:11,670 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004561 finished auxiliary_module.Auxiliary.do_something
Christian Heimes043d6f62008-01-07 17:19:16 +00004562 2005-03-23 23:47:11,671 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004563 calling auxiliary_module.some_function()
Christian Heimes043d6f62008-01-07 17:19:16 +00004564 2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004565 received a call to "some_function"
Christian Heimes043d6f62008-01-07 17:19:16 +00004566 2005-03-23 23:47:11,673 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004567 done with auxiliary_module.some_function()
4568