blob: 25a254930eee6201f986268c628737c9163604b8 [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+=====================================+======================================+
Vinay Sajip9a6b4002010-12-14 19:40:21 +000045| Display console output for ordinary | :func:`print` |
Vinay Sajipa18b9592010-12-12 13:20:55 +000046| usage of a command line script or | |
47| program | |
48+-------------------------------------+--------------------------------------+
Vinay Sajip9a6b4002010-12-14 19:40:21 +000049| Report events that occur during | :func:`logging.info` (or |
50| normal operation of a program (e.g. | :func:`logging.debug` for very |
51| for status monitoring or fault | detailed output for diagnostic |
52| investigation) | purposes) |
Vinay Sajipa18b9592010-12-12 13:20:55 +000053+-------------------------------------+--------------------------------------+
Vinay Sajip9a6b4002010-12-14 19:40:21 +000054| Issue a warning regarding a | :func:`warnings.warn` in library |
55| particular runtime event | code if the issue is avoidable and |
56| | the client application should be |
Vinay Sajipa18b9592010-12-12 13:20:55 +000057| | modified to eliminate the warning |
58| | |
Vinay Sajip9a6b4002010-12-14 19:40:21 +000059| | :func:`logging.warning` if there is |
60| | nothing the client application can do|
61| | about the situation, but the event |
62| | should still be noted |
Vinay Sajipa18b9592010-12-12 13:20:55 +000063+-------------------------------------+--------------------------------------+
64| Report an error regarding a | Raise an exception |
65| particular runtime event | |
66+-------------------------------------+--------------------------------------+
Vinay Sajip9a6b4002010-12-14 19:40:21 +000067| Report suppression of an error | :func:`logging.error`, |
68| without raising an exception (e.g. | :func:`logging.exception` or |
69| error handler in a long-running | :func:`logging.critical` as |
70| server process) | appropriate for the specific error |
71| | and application domain |
Vinay Sajipa18b9592010-12-12 13:20:55 +000072+-------------------------------------+--------------------------------------+
73
74The logging functions are named after the level or severity of the events
75they are used to track. The standard levels and their applicability are
76described below (in increasing order of severity):
77
78+--------------+---------------------------------------------+
79| Level | When it's used |
80+==============+=============================================+
81| ``DEBUG`` | Detailed information, typically of interest |
82| | only when diagnosing problems. |
83+--------------+---------------------------------------------+
84| ``INFO`` | Confirmation that things are working as |
85| | expected. |
86+--------------+---------------------------------------------+
87| ``WARNING`` | An indication that something unexpected |
88| | happened, or indicative of some problem in |
Vinay Sajip9a6b4002010-12-14 19:40:21 +000089| | the near future (e.g. 'disk space low'). |
Vinay Sajipa18b9592010-12-12 13:20:55 +000090| | The software is still working as expected. |
91+--------------+---------------------------------------------+
92| ``ERROR`` | Due to a more serious problem, the software |
93| | has not been able to perform some function. |
94+--------------+---------------------------------------------+
95| ``CRITICAL`` | A serious error, indicating that the program|
96| | itself may be unable to continue running. |
97+--------------+---------------------------------------------+
98
99The default level is ``WARNING``, which means that only events of this level
100and above will be tracked, unless the logging package is configured to do
101otherwise.
102
103Events that are tracked can be handled in different ways. The simplest way of
104handling tracked events is to print them to the console. Another common way
105is to write them to a disk file.
106
107
108.. _minimal-example:
109
110A simple example
111^^^^^^^^^^^^^^^^
112
113A very simple example is::
114
115 import logging
116 logging.warning('Watch out!') # will print a message to the console
117 logging.info('I told you so') # will not print anything
118
119If you type these lines into a script and run it, you'll see::
120
121 WARNING:root:Watch out!
122
123printed out on the console. The ``INFO`` message doesn't appear because the
124default level is ``WARNING``. The printed message includes the indication of
125the level and the description of the event provided in the logging call, i.e.
126'Watch out!'. Don't worry about the 'root' part for now: it will be explained
127later. The actual output can be formatted quite flexibly if you need that;
128formatting options will also be explained later.
129
130
131Logging to a file
132^^^^^^^^^^^^^^^^^
133
134A very common situation is that of recording logging events in a file, so let's
135look at that next::
136
137 import logging
138 logging.basicConfig(filename='example.log',level=logging.DEBUG)
139 logging.debug('This message should go to the log file')
140 logging.info('So should this')
141 logging.warning('And this, too')
142
143And now if we open the file and look at what we have, we should find the log
144messages::
145
146 DEBUG:root:This message should go to the log file
147 INFO:root:So should this
148 WARNING:root:And this, too
149
Vinay Sajip97b886d2010-12-12 22:45:35 +0000150This example also shows how you can set the logging level which acts as the
151threshold for tracking. In this case, because we set the threshold to
152``DEBUG``, all of the messages were printed.
153
154If you want to set the logging level from a command-line option such as::
155
156 --log=INFO
157
158and you have the value of the parameter passed for ``--log`` in some variable
159*loglevel*, you can use::
160
161 getattr(logging, loglevel.upper())
162
163to get the value which you'll pass to :func:`basicConfig` via the *level*
164argument. You may want to error check any user input value, perhaps as in the
165following example::
166
167 # assuming loglevel is bound to the string value obtained from the
168 # command line argument. Convert to upper case to allow the user to
169 # specify --log=DEBUG or --log=debug
170 numeric_level = getattr(logging, loglevel.upper(), None)
Vinay Sajip9466fe82010-12-13 08:54:02 +0000171 if not isinstance(numeric_level, int):
172 raise ValueError('Invalid log level: %s' % loglevel)
Vinay Sajip97b886d2010-12-12 22:45:35 +0000173 logging.basicConfig(level=numeric_level, ...)
174
Vinay Sajip0e65cf02010-12-12 13:49:39 +0000175The call to :func:`basicConfig` should come *before* any calls to :func:`debug`,
176:func:`info` etc. As it's intended as a one-off simple configuration facility,
177only the first call will actually do anything: subsequent calls are effectively
178no-ops.
179
Vinay Sajipa18b9592010-12-12 13:20:55 +0000180If you run the above script several times, the messages from successive runs
181are appended to the file *example.log*. If you want each run to start afresh,
182not remembering the messages from earlier runs, you can specify the *filemode*
183argument, by changing the call in the above example to::
184
185 logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG)
186
187The output will be the same as before, but the log file is no longer appended
188to, so the messages from earlier runs are lost.
189
190
191Logging from multiple modules
192^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
193
194If your program consists of multiple modules, here's an example of how you
195could organize logging in it::
196
197 # myapp.py
198 import logging
199 import mylib
200
201 def main():
202 logging.basicConfig(filename='myapp.log', level=logging.INFO)
203 logging.info('Started')
204 mylib.do_something()
205 logging.info('Finished')
206
207 if __name__ == '__main__':
208 main()
209
210::
211
212 # mylib.py
213 import logging
214
215 def do_something():
216 logging.info('Doing something')
217
Vinay Sajip9a6b4002010-12-14 19:40:21 +0000218If you run *myapp.py*, you should see this in *myapp.log*::
Vinay Sajipa18b9592010-12-12 13:20:55 +0000219
220 INFO:root:Started
221 INFO:root:Doing something
222 INFO:root:Finished
223
224which is hopefully what you were expecting to see. You can generalize this to
225multiple modules, using the pattern in *mylib.py*. Note that for this simple
226usage pattern, you won't know, by looking in the log file, *where* in your
227application your messages came from, apart from looking at the event
228description. If you want to track the location of your messages, you'll need
229to refer to the documentation beyond the tutorial level - see
230:ref:`more-advanced-logging`.
231
232
233Logging variable data
234^^^^^^^^^^^^^^^^^^^^^
235
236To log variable data, use a format string for the event description message and
237append the variable data as arguments. For example::
238
239 import logging
240 logging.warning('%s before you %s', 'Look', 'leap!')
241
242will display::
243
244 WARNING:root:Look before you leap!
245
246As you can see, merging of variable data into the event description message
247uses the old, %-style of string formatting. This is for backwards
248compatibility: the logging package pre-dates newer formatting options such as
Vinay Sajip36675b62010-12-12 22:30:17 +0000249:meth:`str.format` and :class:`string.Template`. These newer formatting
250options *are* supported, but exploring them is outside the scope of this
251tutorial.
Vinay Sajipa18b9592010-12-12 13:20:55 +0000252
253
254Changing the format of displayed messages
255^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
256
257To change the format which is used to display messages, you need to
258specify the format you want to use::
259
260 import logging
261 logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
262 logging.debug('This message should appear on the console')
263 logging.info('So should this')
264 logging.warning('And this, too')
265
266which would print::
267
268 DEBUG:This message should appear on the console
269 INFO:So should this
270 WARNING:And this, too
271
272Notice that the 'root' which appeared in earlier examples has disappeared. For
273a full set of things that can appear in format strings, you can refer to the
Vinay Sajip7292b882010-12-13 18:43:57 +0000274documentation for :ref:`logrecord-attributes`, but for simple usage, you just
275need the *levelname* (severity), *message* (event description, including
276variable data) and perhaps to display when the event occurred. This is
277described in the next section.
278
Vinay Sajipa18b9592010-12-12 13:20:55 +0000279
280Displaying the date/time in messages
281^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
282
Vinay Sajip9a6b4002010-12-14 19:40:21 +0000283To display the date and time of an event, you would place '%(asctime)s' in
Vinay Sajipa18b9592010-12-12 13:20:55 +0000284your format string::
285
286 import logging
287 logging.basicConfig(format='%(asctime)s %(message)s')
288 logging.warning('is when this event was logged.')
289
290which should print something like this::
291
292 2010-12-12 11:41:42,612 is when this event was logged.
293
294The default format for date/time display (shown above) is ISO8601. If you need
295more control over the formatting of the date/time, provide a *datefmt*
296argument to ``basicConfig``, as in this example::
297
298 import logging
299 logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
300 logging.warning('is when this event was logged.')
301
302which would display something like this::
303
304 12/12/2010 11:46:36 AM is when this event was logged.
305
306The format of the *datefmt* argument is the same as supported by
307:func:`time.strftime`.
308
309
Vinay Sajipf234eb92010-12-12 17:37:27 +0000310Er...that's it for the basics
311^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Vinay Sajipa18b9592010-12-12 13:20:55 +0000312
Vinay Sajipf234eb92010-12-12 17:37:27 +0000313That concludes the basic tutorial. It should be enough to get you up and
314running with logging. There's a lot more that the logging package offers, but
315to 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 +0000316reading the following sections. If you're ready for that, grab some of your
317favourite beverage and carry on.
318
319If your logging needs are simple, then use the above examples to incorporate
320logging into your own scripts, and if you run into problems or don't
321understand something, please post a question on the comp.lang.python Usenet
322group (available at http://groups.google.com/group/comp.lang.python) and you
323should receive help before too long.
324
Vinay Sajipf234eb92010-12-12 17:37:27 +0000325Still here? There's no need to read the whole of the logging documentation in
326linear fashion, top to bottom (there's quite a lot of it still to come). You
327can carry on reading the next few sections, which provide a slightly more
328advanced/in-depth tutorial than the basic one above. After that, you can
329take a look at the topics in the sidebar to see if there's something that
330especially interests you, and click on a topic to see more detail. Although
331some of the topics do follow on from each other, there are a few that can just
332stand alone.
Vinay Sajipa18b9592010-12-12 13:20:55 +0000333
334
335.. _more-advanced-logging:
336
337More advanced logging
338---------------------
339
340The logging library takes a modular approach and offers several categories
Vinay Sajip9a6b4002010-12-14 19:40:21 +0000341of components: loggers, handlers, filters, and formatters.
342
343* Loggers expose the interface that application code directly uses.
344* Handlers send the log records (created by loggers) to the appropriate
345 destination.
346* Filters provide a finer grained facility for determining which log records
347 to output.
348* Formatters specify the layout of log records in the final output.
Vinay Sajipa18b9592010-12-12 13:20:55 +0000349
Georg Brandl116aa622007-08-15 14:28:22 +0000350Logging is performed by calling methods on instances of the :class:`Logger`
351class (hereafter called :dfn:`loggers`). Each instance has a name, and they are
Georg Brandl9afde1c2007-11-01 20:32:30 +0000352conceptually arranged in a namespace hierarchy using dots (periods) as
Vinay Sajip9a6b4002010-12-14 19:40:21 +0000353separators. For example, a logger named 'scan' is the parent of loggers
354'scan.text', 'scan.html' and 'scan.pdf'. Logger names can be anything you want,
Georg Brandl116aa622007-08-15 14:28:22 +0000355and indicate the area of an application in which a logged message originates.
356
Vinay Sajip5286ccf2010-12-12 13:25:29 +0000357A good convention to use when naming loggers is to use a module-level logger,
358in each module which uses logging, named as follows::
359
360 logger = logging.getLogger(__name__)
361
362This means that logger names track the package/module hierarchy, and it's
363intuitively obvious where events are logged just from the logger name.
364
Vinay Sajipa18b9592010-12-12 13:20:55 +0000365The root of the hierarchy of loggers is called the root logger. That's the
366logger used by the functions :func:`debug`, :func:`info`, :func:`warning`,
367:func:`error` and :func:`critical`, which just call the same-named method of
368the root logger. The functions and the methods have the same signatures. The
369root logger's name is printed as 'root' in the logged output.
Georg Brandl116aa622007-08-15 14:28:22 +0000370
Vinay Sajipa18b9592010-12-12 13:20:55 +0000371It is, of course, possible to log messages to different destinations. Support
Vinay Sajip9a6b4002010-12-14 19:40:21 +0000372is included in the package for writing log messages to files, HTTP GET/POST
373locations, email via SMTP, generic sockets, queues, or OS-specific logging
374mechanisms such as syslog or the Windows NT event log. Destinations are served
375by :dfn:`handler` classes. You can create your own log destination class if
376you have special requirements not met by any of the built-in handler classes.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000377
Vinay Sajipa18b9592010-12-12 13:20:55 +0000378By default, no destination is set for any logging messages. You can specify
379a destination (such as console or file) by using :func:`basicConfig` as in the
380tutorial examples. If you call the functions :func:`debug`, :func:`info`,
381:func:`warning`, :func:`error` and :func:`critical`, they will check to see
382if no destination is set; and if one is not set, they will set a destination
383of the console (``sys.stderr``) and a default format for the displayed
384message before delegating to the root logger to do the actual message output.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000385
Vinay Sajipa18b9592010-12-12 13:20:55 +0000386The default format set by :func:`basicConfig` for messages is::
Christian Heimes8b0facf2007-12-04 19:30:01 +0000387
Vinay Sajipa18b9592010-12-12 13:20:55 +0000388 severity:logger name:message
Christian Heimes8b0facf2007-12-04 19:30:01 +0000389
Vinay Sajipa18b9592010-12-12 13:20:55 +0000390You can change this by passing a format string to :func:`basicConfig` with the
391*format* keyword argument. For all options regarding how a format string is
392constructed, see :ref:`formatter-objects`.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000393
Christian Heimes8b0facf2007-12-04 19:30:01 +0000394
395Loggers
396^^^^^^^
397
Christian Heimes8b0facf2007-12-04 19:30:01 +0000398:class:`Logger` objects have a threefold job. First, they expose several
399methods to application code so that applications can log messages at runtime.
400Second, logger objects determine which log messages to act upon based upon
401severity (the default filtering facility) or filter objects. Third, logger
402objects pass along relevant log messages to all interested log handlers.
403
404The most widely used methods on logger objects fall into two categories:
405configuration and message sending.
406
Vinay Sajipf234eb92010-12-12 17:37:27 +0000407These are the most common configuration methods:
408
Christian Heimes8b0facf2007-12-04 19:30:01 +0000409* :meth:`Logger.setLevel` specifies the lowest-severity log message a logger
Vinay Sajipf234eb92010-12-12 17:37:27 +0000410 will handle, where debug is the lowest built-in severity level and critical
411 is the highest built-in severity. For example, if the severity level is
412 INFO, the logger will handle only INFO, WARNING, ERROR, and CRITICAL messages
413 and will ignore DEBUG messages.
414
415* :meth:`Logger.addHandler` and :meth:`Logger.removeHandler` add and remove
416 handler objects from the logger object. Handlers are covered in more detail
417 in :ref:`handler-basic`.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000418
419* :meth:`Logger.addFilter` and :meth:`Logger.removeFilter` add and remove filter
Vinay Sajipf234eb92010-12-12 17:37:27 +0000420 objects from the logger object. Filters are covered in more detail in
421 :ref:`filter`.
422
423You don't need to always call these methods on every logger you create. See the
424last two paragraphs in this section.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000425
426With the logger object configured, the following methods create log messages:
427
428* :meth:`Logger.debug`, :meth:`Logger.info`, :meth:`Logger.warning`,
429 :meth:`Logger.error`, and :meth:`Logger.critical` all create log records with
430 a message and a level that corresponds to their respective method names. The
431 message is actually a format string, which may contain the standard string
432 substitution syntax of :const:`%s`, :const:`%d`, :const:`%f`, and so on. The
433 rest of their arguments is a list of objects that correspond with the
434 substitution fields in the message. With regard to :const:`**kwargs`, the
435 logging methods care only about a keyword of :const:`exc_info` and use it to
436 determine whether to log exception information.
437
438* :meth:`Logger.exception` creates a log message similar to
439 :meth:`Logger.error`. The difference is that :meth:`Logger.exception` dumps a
440 stack trace along with it. Call this method only from an exception handler.
441
442* :meth:`Logger.log` takes a log level as an explicit argument. This is a
443 little more verbose for logging messages than using the log level convenience
444 methods listed above, but this is how to log at custom log levels.
445
Christian Heimesdcca98d2008-02-25 13:19:43 +0000446:func:`getLogger` returns a reference to a logger instance with the specified
Vinay Sajipc15dfd62010-07-06 15:08:55 +0000447name if it is provided, or ``root`` if not. The names are period-separated
Christian Heimes8b0facf2007-12-04 19:30:01 +0000448hierarchical structures. Multiple calls to :func:`getLogger` with the same name
449will return a reference to the same logger object. Loggers that are further
450down in the hierarchical list are children of loggers higher up in the list.
451For example, given a logger with a name of ``foo``, loggers with names of
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000452``foo.bar``, ``foo.bar.baz``, and ``foo.bam`` are all descendants of ``foo``.
Vinay Sajipf234eb92010-12-12 17:37:27 +0000453
454Loggers have a concept of *effective level*. If a level is not explicitly set
455on a logger, the level of its parent is used instead as its effective level.
456If the parent has no explicit level set, *its* parent is examined, and so on -
457all ancestors are searched until an explicitly set level is found. The root
458logger always has an explicit level set (``WARNING`` by default). When deciding
459whether to process an event, the effective level of the logger is used to
460determine whether the event is passed to the logger's handlers.
461
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000462Child loggers propagate messages up to the handlers associated with their
Vinay Sajipf234eb92010-12-12 17:37:27 +0000463ancestor loggers. Because of this, it is unnecessary to define and configure
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000464handlers for all the loggers an application uses. It is sufficient to
465configure handlers for a top-level logger and create child loggers as needed.
Vinay Sajipf234eb92010-12-12 17:37:27 +0000466(You can, however, turn off propagation by setting the *propagate*
467attribute of a logger to *False*.)
Christian Heimes8b0facf2007-12-04 19:30:01 +0000468
469
Vinay Sajipf234eb92010-12-12 17:37:27 +0000470.. _handler-basic:
471
Christian Heimes8b0facf2007-12-04 19:30:01 +0000472Handlers
473^^^^^^^^
474
475:class:`Handler` objects are responsible for dispatching the appropriate log
476messages (based on the log messages' severity) to the handler's specified
477destination. Logger objects can add zero or more handler objects to themselves
478with an :func:`addHandler` method. As an example scenario, an application may
479want to send all log messages to a log file, all log messages of error or higher
480to stdout, and all messages of critical to an email address. This scenario
Christian Heimesc3f30c42008-02-22 16:37:40 +0000481requires three individual handlers where each handler is responsible for sending
Christian Heimes8b0facf2007-12-04 19:30:01 +0000482messages of a specific severity to a specific location.
483
Vinay Sajipf234eb92010-12-12 17:37:27 +0000484The standard library includes quite a few handler types (see
485:ref:`useful-handlers`); the tutorials use mainly :class:`StreamHandler` and
486:class:`FileHandler` in its examples.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000487
488There are very few methods in a handler for application developers to concern
489themselves with. The only handler methods that seem relevant for application
490developers who are using the built-in handler objects (that is, not creating
491custom handlers) are the following configuration methods:
492
493* The :meth:`Handler.setLevel` method, just as in logger objects, specifies the
494 lowest severity that will be dispatched to the appropriate destination. Why
495 are there two :func:`setLevel` methods? The level set in the logger
496 determines which severity of messages it will pass to its handlers. The level
497 set in each handler determines which messages that handler will send on.
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000498
499* :func:`setFormatter` selects a Formatter object for this handler to use.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000500
501* :func:`addFilter` and :func:`removeFilter` respectively configure and
502 deconfigure filter objects on handlers.
503
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000504Application code should not directly instantiate and use instances of
505:class:`Handler`. Instead, the :class:`Handler` class is a base class that
506defines the interface that all handlers should have and establishes some
507default behavior that child classes can use (or override).
Christian Heimes8b0facf2007-12-04 19:30:01 +0000508
509
510Formatters
511^^^^^^^^^^
512
513Formatter objects configure the final order, structure, and contents of the log
Christian Heimesdcca98d2008-02-25 13:19:43 +0000514message. Unlike the base :class:`logging.Handler` class, application code may
Christian Heimes8b0facf2007-12-04 19:30:01 +0000515instantiate formatter classes, although you could likely subclass the formatter
Vinay Sajipa39c5712010-10-25 13:57:39 +0000516if your application needs special behavior. The constructor takes three
517optional arguments -- a message format string, a date format string and a style
518indicator.
519
520.. method:: logging.Formatter.__init__(fmt=None, datefmt=None, style='%')
521
522If there is no message format string, the default is to use the
523raw message. If there is no date format string, the default date format is::
Christian Heimes8b0facf2007-12-04 19:30:01 +0000524
525 %Y-%m-%d %H:%M:%S
526
Vinay Sajipa39c5712010-10-25 13:57:39 +0000527with the milliseconds tacked on at the end. The ``style`` is one of `%`, '{'
528or '$'. If one of these is not specified, then '%' will be used.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000529
Vinay Sajipa39c5712010-10-25 13:57:39 +0000530If the ``style`` is '%', the message format string uses
531``%(<dictionary key>)s`` styled string substitution; the possible keys are
Vinay Sajip7292b882010-12-13 18:43:57 +0000532documented in :ref:`logrecord-attributes`. If the style is '{', the message
533format string is assumed to be compatible with :meth:`str.format` (using
534keyword arguments), while if the style is '$' then the message format string
535should conform to what is expected by :meth:`string.Template.substitute`.
Vinay Sajipa39c5712010-10-25 13:57:39 +0000536
537.. versionchanged:: 3.2
538 Added the ``style`` parameter.
Christian Heimes8b0facf2007-12-04 19:30:01 +0000539
540The following message format string will log the time in a human-readable
541format, the severity of the message, and the contents of the message, in that
542order::
543
Vinay Sajip9a6b4002010-12-14 19:40:21 +0000544 '%(asctime)s - %(levelname)s - %(message)s'
Christian Heimes8b0facf2007-12-04 19:30:01 +0000545
Vinay Sajip40d9a4e2010-08-30 18:10:03 +0000546Formatters use a user-configurable function to convert the creation time of a
547record to a tuple. By default, :func:`time.localtime` is used; to change this
548for a particular formatter instance, set the ``converter`` attribute of the
549instance to a function with the same signature as :func:`time.localtime` or
550:func:`time.gmtime`. To change it for all formatters, for example if you want
551all logging times to be shown in GMT, set the ``converter`` attribute in the
552Formatter class (to ``time.gmtime`` for GMT display).
553
Christian Heimes8b0facf2007-12-04 19:30:01 +0000554
555Configuring Logging
556^^^^^^^^^^^^^^^^^^^
557
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000558Programmers can configure logging in three ways:
559
5601. Creating loggers, handlers, and formatters explicitly using Python
561 code that calls the configuration methods listed above.
5622. Creating a logging config file and reading it using the :func:`fileConfig`
563 function.
5643. Creating a dictionary of configuration information and passing it
565 to the :func:`dictConfig` function.
566
Vinay Sajip75043022010-12-19 06:02:31 +0000567For the reference documentation on the last two options, see :ref:`config-ref`.
568The following example configures a very simple logger, a console handler, and
569a simple formatter using Python code::
Christian Heimes8b0facf2007-12-04 19:30:01 +0000570
571 import logging
572
573 # create logger
Vinay Sajip9a6b4002010-12-14 19:40:21 +0000574 logger = logging.getLogger('simple_example')
Christian Heimes8b0facf2007-12-04 19:30:01 +0000575 logger.setLevel(logging.DEBUG)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000576
Christian Heimes8b0facf2007-12-04 19:30:01 +0000577 # create console handler and set level to debug
578 ch = logging.StreamHandler()
579 ch.setLevel(logging.DEBUG)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000580
Christian Heimes8b0facf2007-12-04 19:30:01 +0000581 # create formatter
Vinay Sajip9a6b4002010-12-14 19:40:21 +0000582 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000583
Christian Heimes8b0facf2007-12-04 19:30:01 +0000584 # add formatter to ch
585 ch.setFormatter(formatter)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000586
Christian Heimes8b0facf2007-12-04 19:30:01 +0000587 # add ch to logger
588 logger.addHandler(ch)
589
Vinay Sajip9a6b4002010-12-14 19:40:21 +0000590 # 'application' code
591 logger.debug('debug message')
592 logger.info('info message')
593 logger.warn('warn message')
594 logger.error('error message')
595 logger.critical('critical message')
Christian Heimes8b0facf2007-12-04 19:30:01 +0000596
597Running this module from the command line produces the following output::
598
599 $ python simple_logging_module.py
600 2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
601 2005-03-19 15:10:26,620 - simple_example - INFO - info message
602 2005-03-19 15:10:26,695 - simple_example - WARNING - warn message
603 2005-03-19 15:10:26,697 - simple_example - ERROR - error message
604 2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message
605
606The following Python module creates a logger, handler, and formatter nearly
607identical to those in the example listed above, with the only difference being
608the names of the objects::
609
610 import logging
611 import logging.config
612
Vinay Sajip9a6b4002010-12-14 19:40:21 +0000613 logging.config.fileConfig('logging.conf')
Christian Heimes8b0facf2007-12-04 19:30:01 +0000614
615 # create logger
Vinay Sajip9a6b4002010-12-14 19:40:21 +0000616 logger = logging.getLogger('simpleExample')
Christian Heimes8b0facf2007-12-04 19:30:01 +0000617
Vinay Sajip9a6b4002010-12-14 19:40:21 +0000618 # 'application' code
619 logger.debug('debug message')
620 logger.info('info message')
621 logger.warn('warn message')
622 logger.error('error message')
623 logger.critical('critical message')
Christian Heimes8b0facf2007-12-04 19:30:01 +0000624
625Here is the logging.conf file::
626
627 [loggers]
628 keys=root,simpleExample
629
630 [handlers]
631 keys=consoleHandler
632
633 [formatters]
634 keys=simpleFormatter
635
636 [logger_root]
637 level=DEBUG
638 handlers=consoleHandler
639
640 [logger_simpleExample]
641 level=DEBUG
642 handlers=consoleHandler
643 qualname=simpleExample
644 propagate=0
645
646 [handler_consoleHandler]
647 class=StreamHandler
648 level=DEBUG
649 formatter=simpleFormatter
650 args=(sys.stdout,)
651
652 [formatter_simpleFormatter]
653 format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
654 datefmt=
655
656The output is nearly identical to that of the non-config-file-based example::
657
658 $ python simple_logging_config.py
659 2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
660 2005-03-19 15:38:55,979 - simpleExample - INFO - info message
661 2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
662 2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
663 2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message
664
665You can see that the config file approach has a few advantages over the Python
666code approach, mainly separation of configuration and code and the ability of
667noncoders to easily modify the logging properties.
668
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000669Note that the class names referenced in config files need to be either relative
670to the logging module, or absolute values which can be resolved using normal
Senthil Kumaran46a48be2010-10-15 13:10:10 +0000671import mechanisms. Thus, you could use either
672:class:`handlers.WatchedFileHandler` (relative to the logging module) or
673``mypackage.mymodule.MyHandler`` (for a class defined in package ``mypackage``
674and module ``mymodule``, where ``mypackage`` is available on the Python import
675path).
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000676
Benjamin Peterson56894b52010-06-28 00:16:12 +0000677In Python 3.2, a new means of configuring logging has been introduced, using
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000678dictionaries to hold configuration information. This provides a superset of the
679functionality of the config-file-based approach outlined above, and is the
680recommended configuration method for new applications and deployments. Because
681a Python dictionary is used to hold configuration information, and since you
682can populate that dictionary using different means, you have more options for
683configuration. For example, you can use a configuration file in JSON format,
684or, if you have access to YAML processing functionality, a file in YAML
685format, to populate the configuration dictionary. Or, of course, you can
686construct the dictionary in Python code, receive it in pickled form over a
687socket, or use whatever approach makes sense for your application.
688
689Here's an example of the same configuration as above, in YAML format for
690the new dictionary-based approach::
691
692 version: 1
693 formatters:
694 simple:
695 format: format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
696 handlers:
697 console:
698 class: logging.StreamHandler
699 level: DEBUG
700 formatter: simple
701 stream: ext://sys.stdout
702 loggers:
703 simpleExample:
704 level: DEBUG
705 handlers: [console]
706 propagate: no
707 root:
Vinay Sajip75043022010-12-19 06:02:31 +0000708 level: DEBUG
709 handlers: [console]
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000710
711For more information about logging using a dictionary, see
712:ref:`logging-config-api`.
713
Vinay Sajipf234eb92010-12-12 17:37:27 +0000714What happens if no configuration is provided
715^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
716
717If no logging configuration is provided, it is possible to have a situation
718where a logging event needs to be output, but no handlers can be found to
719output the event. The behaviour of the logging package in these
720circumstances is dependent on the Python version.
721
722For versions of Python prior to 3.2, the behaviour is as follows:
723
724* If *logging.raiseExceptions* is *False* (production mode), the event is
725 silently dropped.
726
727* If *logging.raiseExceptions* is *True* (development mode), a message
Vinay Sajip9a6b4002010-12-14 19:40:21 +0000728 'No handlers could be found for logger X.Y.Z' is printed once.
Vinay Sajipf234eb92010-12-12 17:37:27 +0000729
730In Python 3.2 and later, the behaviour is as follows:
731
Vinay Sajip9a6b4002010-12-14 19:40:21 +0000732* The event is output using a 'handler of last resort', stored in
Vinay Sajipf234eb92010-12-12 17:37:27 +0000733 ``logging.lastResort``. This internal handler is not associated with any
734 logger, and acts like a :class:`StreamHandler` which writes the event
735 description message to the current value of ``sys.stderr`` (therefore
736 respecting any redirections which may be in effect). No formatting is
737 done on the message - just the bare event description message is printed.
738 The handler's level is set to ``WARNING``, so all events at this and
739 greater severities will be output.
740
741To obtain the pre-3.2 behaviour, ``logging.lastResort`` can be set to *None*.
742
Vinay Sajip26a2d5e2009-01-10 13:37:26 +0000743.. _library-config:
Vinay Sajip30bf1222009-01-10 19:23:34 +0000744
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000745Configuring Logging for a Library
746^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
747
Vinay Sajipf234eb92010-12-12 17:37:27 +0000748When developing a library which uses logging, you should take care to
749document how the library uses logging - for example, the names of loggers
750used. Some consideration also needs to be given to its logging configuration.
751If the using application does not use logging, and library code makes logging
752calls, then (as described in the previous section) events of severity
753``WARNING`` and greater will be printed to ``sys.stderr``. This is regarded as
754the best default behaviour.
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000755
Vinay Sajipf234eb92010-12-12 17:37:27 +0000756If for some reason you *don't* want these messages printed in the absence of
757any logging configuration, you can attach a do-nothing handler to the top-level
758logger for your library. This avoids the message being printed, since a handler
759will be always be found for the library's events: it just doesn't produce any
760output. If the library user configures logging for application use, presumably
761that configuration will add some handlers, and if levels are suitably
762configured then logging calls made in library code will send output to those
763handlers, as normal.
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000764
Vinay Sajipf234eb92010-12-12 17:37:27 +0000765A do-nothing handler is included in the logging package: :class:`NullHandler`
766(since Python 3.1). An instance of this handler could be added to the top-level
767logger of the logging namespace used by the library (*if* you want to prevent
768your library's logged events being output to ``sys.stderr`` in the absence of
769logging configuration). If all logging by a library *foo* is done using loggers
770with names matching 'foo.x', 'foo.x.y', etc. then the code::
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000771
772 import logging
Vinay Sajipf234eb92010-12-12 17:37:27 +0000773 logging.getLogger('foo').addHandler(logging.NullHandler())
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000774
775should have the desired effect. If an organisation produces a number of
Vinay Sajipf234eb92010-12-12 17:37:27 +0000776libraries, then the logger name specified can be 'orgname.foo' rather than
777just 'foo'.
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000778
Vinay Sajip76ca3b42010-09-27 13:53:47 +0000779**PLEASE NOTE:** It is strongly advised that you *do not add any handlers other
780than* :class:`NullHandler` *to your library's loggers*. This is because the
781configuration of handlers is the prerogative of the application developer who
782uses your library. The application developer knows their target audience and
783what handlers are most appropriate for their application: if you add handlers
Vinay Sajip9a6b4002010-12-14 19:40:21 +0000784'under the hood', you might well interfere with their ability to carry out
Vinay Sajip76ca3b42010-09-27 13:53:47 +0000785unit tests and deliver logs which suit their requirements.
786
Christian Heimes8b0facf2007-12-04 19:30:01 +0000787
788Logging Levels
789--------------
790
Georg Brandl116aa622007-08-15 14:28:22 +0000791The numeric values of logging levels are given in the following table. These are
792primarily of interest if you want to define your own levels, and need them to
793have specific values relative to the predefined levels. If you define a level
794with the same numeric value, it overwrites the predefined value; the predefined
795name is lost.
796
797+--------------+---------------+
798| Level | Numeric value |
799+==============+===============+
800| ``CRITICAL`` | 50 |
801+--------------+---------------+
802| ``ERROR`` | 40 |
803+--------------+---------------+
804| ``WARNING`` | 30 |
805+--------------+---------------+
806| ``INFO`` | 20 |
807+--------------+---------------+
808| ``DEBUG`` | 10 |
809+--------------+---------------+
810| ``NOTSET`` | 0 |
811+--------------+---------------+
812
813Levels can also be associated with loggers, being set either by the developer or
814through loading a saved logging configuration. When a logging method is called
815on a logger, the logger compares its own level with the level associated with
816the method call. If the logger's level is higher than the method call's, no
817logging message is actually generated. This is the basic mechanism controlling
818the verbosity of logging output.
819
820Logging messages are encoded as instances of the :class:`LogRecord` class. When
821a logger decides to actually log an event, a :class:`LogRecord` instance is
822created from the logging message.
823
824Logging messages are subjected to a dispatch mechanism through the use of
825:dfn:`handlers`, which are instances of subclasses of the :class:`Handler`
826class. Handlers are responsible for ensuring that a logged message (in the form
827of a :class:`LogRecord`) ends up in a particular location (or set of locations)
828which is useful for the target audience for that message (such as end users,
829support desk staff, system administrators, developers). Handlers are passed
830:class:`LogRecord` instances intended for particular destinations. Each logger
831can have zero, one or more handlers associated with it (via the
832:meth:`addHandler` method of :class:`Logger`). In addition to any handlers
833directly associated with a logger, *all handlers associated with all ancestors
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000834of the logger* are called to dispatch the message (unless the *propagate* flag
835for a logger is set to a false value, at which point the passing to ancestor
836handlers stops).
Georg Brandl116aa622007-08-15 14:28:22 +0000837
838Just as for loggers, handlers can have levels associated with them. A handler's
839level acts as a filter in the same way as a logger's level does. If a handler
840decides to actually dispatch an event, the :meth:`emit` method is used to send
841the message to its destination. Most user-defined subclasses of :class:`Handler`
842will need to override this :meth:`emit`.
843
Vinay Sajipc8c8c692010-09-17 10:09:04 +0000844.. _custom-levels:
845
846Custom Levels
847^^^^^^^^^^^^^
848
849Defining your own levels is possible, but should not be necessary, as the
850existing levels have been chosen on the basis of practical experience.
851However, if you are convinced that you need custom levels, great care should
852be exercised when doing this, and it is possibly *a very bad idea to define
853custom levels if you are developing a library*. That's because if multiple
854library authors all define their own custom levels, there is a chance that
855the logging output from such multiple libraries used together will be
856difficult for the using developer to control and/or interpret, because a
857given numeric value might mean different things for different libraries.
858
859
Vinay Sajipf234eb92010-12-12 17:37:27 +0000860.. _useful-handlers:
861
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000862Useful Handlers
863---------------
864
Georg Brandl116aa622007-08-15 14:28:22 +0000865In addition to the base :class:`Handler` class, many useful subclasses are
866provided:
867
Vinay Sajip121a1c42010-09-08 10:46:15 +0000868#. :class:`StreamHandler` instances send messages to streams (file-like
Georg Brandl116aa622007-08-15 14:28:22 +0000869 objects).
870
Vinay Sajip121a1c42010-09-08 10:46:15 +0000871#. :class:`FileHandler` instances send messages to disk files.
Georg Brandl116aa622007-08-15 14:28:22 +0000872
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000873.. module:: logging.handlers
Vinay Sajip30bf1222009-01-10 19:23:34 +0000874
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000875#. :class:`BaseRotatingHandler` is the base class for handlers that
876 rotate log files at a certain point. It is not meant to be instantiated
877 directly. Instead, use :class:`RotatingFileHandler` or
878 :class:`TimedRotatingFileHandler`.
Georg Brandl116aa622007-08-15 14:28:22 +0000879
Vinay Sajip121a1c42010-09-08 10:46:15 +0000880#. :class:`RotatingFileHandler` instances send messages to disk
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000881 files, with support for maximum log file sizes and log file rotation.
Georg Brandl116aa622007-08-15 14:28:22 +0000882
Vinay Sajip121a1c42010-09-08 10:46:15 +0000883#. :class:`TimedRotatingFileHandler` instances send messages to
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000884 disk files, rotating the log file at certain timed intervals.
Georg Brandl116aa622007-08-15 14:28:22 +0000885
Vinay Sajip121a1c42010-09-08 10:46:15 +0000886#. :class:`SocketHandler` instances send messages to TCP/IP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000887 sockets.
Georg Brandl116aa622007-08-15 14:28:22 +0000888
Vinay Sajip121a1c42010-09-08 10:46:15 +0000889#. :class:`DatagramHandler` instances send messages to UDP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000890 sockets.
Georg Brandl116aa622007-08-15 14:28:22 +0000891
Vinay Sajip121a1c42010-09-08 10:46:15 +0000892#. :class:`SMTPHandler` instances send messages to a designated
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000893 email address.
Georg Brandl116aa622007-08-15 14:28:22 +0000894
Vinay Sajip121a1c42010-09-08 10:46:15 +0000895#. :class:`SysLogHandler` instances send messages to a Unix
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000896 syslog daemon, possibly on a remote machine.
Georg Brandl116aa622007-08-15 14:28:22 +0000897
Vinay Sajip121a1c42010-09-08 10:46:15 +0000898#. :class:`NTEventLogHandler` instances send messages to a
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000899 Windows NT/2000/XP event log.
Georg Brandl116aa622007-08-15 14:28:22 +0000900
Vinay Sajip121a1c42010-09-08 10:46:15 +0000901#. :class:`MemoryHandler` instances send messages to a buffer
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000902 in memory, which is flushed whenever specific criteria are met.
Georg Brandl116aa622007-08-15 14:28:22 +0000903
Vinay Sajip121a1c42010-09-08 10:46:15 +0000904#. :class:`HTTPHandler` instances send messages to an HTTP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000905 server using either ``GET`` or ``POST`` semantics.
Georg Brandl116aa622007-08-15 14:28:22 +0000906
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000907#. :class:`WatchedFileHandler` instances watch the file they are
908 logging to. If the file changes, it is closed and reopened using the file
909 name. This handler is only useful on Unix-like systems; Windows does not
910 support the underlying mechanism used.
Vinay Sajip30bf1222009-01-10 19:23:34 +0000911
Vinay Sajip121a1c42010-09-08 10:46:15 +0000912#. :class:`QueueHandler` instances send messages to a queue, such as
913 those implemented in the :mod:`queue` or :mod:`multiprocessing` modules.
914
Vinay Sajip30bf1222009-01-10 19:23:34 +0000915.. currentmodule:: logging
916
Georg Brandlf9734072008-12-07 15:30:06 +0000917#. :class:`NullHandler` instances do nothing with error messages. They are used
Vinay Sajip9a6b4002010-12-14 19:40:21 +0000918 by library developers who want to use logging, but want to avoid the 'No
919 handlers could be found for logger XXX' message which can be displayed if
Vinay Sajip26a2d5e2009-01-10 13:37:26 +0000920 the library user has not configured logging. See :ref:`library-config` for
921 more information.
Georg Brandlf9734072008-12-07 15:30:06 +0000922
923.. versionadded:: 3.1
Georg Brandl1eb40bc2010-12-03 15:30:09 +0000924 The :class:`NullHandler` class.
Georg Brandlf9734072008-12-07 15:30:06 +0000925
Vinay Sajip121a1c42010-09-08 10:46:15 +0000926.. versionadded:: 3.2
Vinay Sajipa18b9592010-12-12 13:20:55 +0000927 The :class:`~logging.handlers.QueueHandler` class.
Vinay Sajip121a1c42010-09-08 10:46:15 +0000928
Vinay Sajipa17775f2008-12-30 07:32:59 +0000929The :class:`NullHandler`, :class:`StreamHandler` and :class:`FileHandler`
930classes are defined in the core logging package. The other handlers are
931defined in a sub- module, :mod:`logging.handlers`. (There is also another
932sub-module, :mod:`logging.config`, for configuration functionality.)
Georg Brandl116aa622007-08-15 14:28:22 +0000933
934Logged messages are formatted for presentation through instances of the
935:class:`Formatter` class. They are initialized with a format string suitable for
936use with the % operator and a dictionary.
937
938For formatting multiple messages in a batch, instances of
939:class:`BufferingFormatter` can be used. In addition to the format string (which
940is applied to each message in the batch), there is provision for header and
941trailer format strings.
942
943When filtering based on logger level and/or handler level is not enough,
944instances of :class:`Filter` can be added to both :class:`Logger` and
945:class:`Handler` instances (through their :meth:`addFilter` method). Before
946deciding to process a message further, both loggers and handlers consult all
947their filters for permission. If any filter returns a false value, the message
948is not processed further.
949
950The basic :class:`Filter` functionality allows filtering by specific logger
951name. If this feature is used, messages sent to the named logger and its
952children are allowed through the filter, and all others dropped.
953
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000954Module-Level Functions
955----------------------
956
Georg Brandl116aa622007-08-15 14:28:22 +0000957In addition to the classes described above, there are a number of module- level
958functions.
959
960
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000961.. function:: getLogger(name=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000962
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000963 Return a logger with the specified name or, if name is ``None``, return a
Georg Brandl116aa622007-08-15 14:28:22 +0000964 logger which is the root logger of the hierarchy. If specified, the name is
Vinay Sajip9a6b4002010-12-14 19:40:21 +0000965 typically a dot-separated hierarchical name like *'a'*, *'a.b'* or *'a.b.c.d'*.
Georg Brandl116aa622007-08-15 14:28:22 +0000966 Choice of these names is entirely up to the developer who is using logging.
967
968 All calls to this function with a given name return the same logger instance.
969 This means that logger instances never need to be passed between different parts
970 of an application.
971
972
973.. function:: getLoggerClass()
974
975 Return either the standard :class:`Logger` class, or the last class passed to
976 :func:`setLoggerClass`. This function may be called from within a new class
977 definition, to ensure that installing a customised :class:`Logger` class will
978 not undo customisations already applied by other code. For example::
979
980 class MyLogger(logging.getLoggerClass()):
981 # ... override behaviour here
982
983
Vinay Sajip61561522010-12-03 11:50:38 +0000984.. function:: getLogRecordFactory()
985
986 Return a callable which is used to create a :class:`LogRecord`.
987
988 .. versionadded:: 3.2
Vinay Sajip61561522010-12-03 11:50:38 +0000989 This function has been provided, along with :func:`setLogRecordFactory`,
990 to allow developers more control over how the :class:`LogRecord`
991 representing a logging event is constructed.
992
993 See :func:`setLogRecordFactory` for more information about the how the
994 factory is called.
995
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000996.. function:: debug(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000997
998 Logs a message with level :const:`DEBUG` on the root logger. The *msg* is the
999 message format string, and the *args* are the arguments which are merged into
1000 *msg* using the string formatting operator. (Note that this means that you can
1001 use keywords in the format string, together with a single dictionary argument.)
1002
Vinay Sajip8593ae62010-11-14 21:33:04 +00001003 There are three keyword arguments in *kwargs* which are inspected: *exc_info*
Georg Brandl116aa622007-08-15 14:28:22 +00001004 which, if it does not evaluate as false, causes exception information to be
1005 added to the logging message. If an exception tuple (in the format returned by
1006 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
1007 is called to get the exception information.
1008
Vinay Sajip8593ae62010-11-14 21:33:04 +00001009 The second optional keyword argument is *stack_info*, which defaults to
1010 False. If specified as True, stack information is added to the logging
1011 message, including the actual logging call. Note that this is not the same
1012 stack information as that displayed through specifying *exc_info*: The
1013 former is stack frames from the bottom of the stack up to the logging call
1014 in the current thread, whereas the latter is information about stack frames
1015 which have been unwound, following an exception, while searching for
1016 exception handlers.
1017
1018 You can specify *stack_info* independently of *exc_info*, e.g. to just show
1019 how you got to a certain point in your code, even when no exceptions were
1020 raised. The stack frames are printed following a header line which says::
1021
1022 Stack (most recent call last):
1023
1024 This mimics the `Traceback (most recent call last):` which is used when
1025 displaying exception frames.
1026
1027 The third optional keyword argument is *extra* which can be used to pass a
Georg Brandl116aa622007-08-15 14:28:22 +00001028 dictionary which is used to populate the __dict__ of the LogRecord created for
1029 the logging event with user-defined attributes. These custom attributes can then
1030 be used as you like. For example, they could be incorporated into logged
1031 messages. For example::
1032
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001033 FORMAT = '%(asctime)-15s %(clientip)s %(user)-8s %(message)s'
Georg Brandl116aa622007-08-15 14:28:22 +00001034 logging.basicConfig(format=FORMAT)
1035 d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001036 logging.warning('Protocol problem: %s', 'connection reset', extra=d)
Georg Brandl116aa622007-08-15 14:28:22 +00001037
Vinay Sajip4039aff2010-09-11 10:25:28 +00001038 would print something like::
Georg Brandl116aa622007-08-15 14:28:22 +00001039
1040 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
1041
1042 The keys in the dictionary passed in *extra* should not clash with the keys used
1043 by the logging system. (See the :class:`Formatter` documentation for more
1044 information on which keys are used by the logging system.)
1045
1046 If you choose to use these attributes in logged messages, you need to exercise
1047 some care. In the above example, for instance, the :class:`Formatter` has been
1048 set up with a format string which expects 'clientip' and 'user' in the attribute
1049 dictionary of the LogRecord. If these are missing, the message will not be
1050 logged because a string formatting exception will occur. So in this case, you
1051 always need to pass the *extra* dictionary with these keys.
1052
1053 While this might be annoying, this feature is intended for use in specialized
1054 circumstances, such as multi-threaded servers where the same code executes in
1055 many contexts, and interesting conditions which arise are dependent on this
1056 context (such as remote client IP address and authenticated user name, in the
1057 above example). In such circumstances, it is likely that specialized
1058 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
1059
Vinay Sajip8593ae62010-11-14 21:33:04 +00001060 .. versionadded:: 3.2
1061 The *stack_info* parameter was added.
Georg Brandl116aa622007-08-15 14:28:22 +00001062
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001063.. function:: info(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001064
1065 Logs a message with level :const:`INFO` on the root logger. The arguments are
1066 interpreted as for :func:`debug`.
1067
1068
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001069.. function:: warning(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001070
1071 Logs a message with level :const:`WARNING` on the root logger. The arguments are
1072 interpreted as for :func:`debug`.
1073
1074
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001075.. function:: error(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001076
1077 Logs a message with level :const:`ERROR` on the root logger. The arguments are
1078 interpreted as for :func:`debug`.
1079
1080
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001081.. function:: critical(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001082
1083 Logs a message with level :const:`CRITICAL` on the root logger. The arguments
1084 are interpreted as for :func:`debug`.
1085
1086
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001087.. function:: exception(msg, *args)
Georg Brandl116aa622007-08-15 14:28:22 +00001088
1089 Logs a message with level :const:`ERROR` on the root logger. The arguments are
1090 interpreted as for :func:`debug`. Exception info is added to the logging
1091 message. This function should only be called from an exception handler.
1092
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001093.. function:: log(level, msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001094
1095 Logs a message with level *level* on the root logger. The other arguments are
1096 interpreted as for :func:`debug`.
1097
Vinay Sajipc8c8c692010-09-17 10:09:04 +00001098 PLEASE NOTE: The above module-level functions which delegate to the root
1099 logger should *not* be used in threads, in versions of Python earlier than
1100 2.7.1 and 3.2, unless at least one handler has been added to the root
1101 logger *before* the threads are started. These convenience functions call
1102 :func:`basicConfig` to ensure that at least one handler is available; in
1103 earlier versions of Python, this can (under rare circumstances) lead to
1104 handlers being added multiple times to the root logger, which can in turn
1105 lead to multiple messages for the same event.
Georg Brandl116aa622007-08-15 14:28:22 +00001106
1107.. function:: disable(lvl)
1108
1109 Provides an overriding level *lvl* for all loggers which takes precedence over
1110 the logger's own level. When the need arises to temporarily throttle logging
Benjamin Peterson886af962010-03-21 23:13:07 +00001111 output down across the whole application, this function can be useful. Its
1112 effect is to disable all logging calls of severity *lvl* and below, so that
1113 if you call it with a value of INFO, then all INFO and DEBUG events would be
1114 discarded, whereas those of severity WARNING and above would be processed
1115 according to the logger's effective level.
Georg Brandl116aa622007-08-15 14:28:22 +00001116
1117
1118.. function:: addLevelName(lvl, levelName)
1119
1120 Associates level *lvl* with text *levelName* in an internal dictionary, which is
1121 used to map numeric levels to a textual representation, for example when a
1122 :class:`Formatter` formats a message. This function can also be used to define
1123 your own levels. The only constraints are that all levels used must be
1124 registered using this function, levels should be positive integers and they
1125 should increase in increasing order of severity.
1126
Vinay Sajipc8c8c692010-09-17 10:09:04 +00001127 NOTE: If you are thinking of defining your own levels, please see the section
1128 on :ref:`custom-levels`.
Georg Brandl116aa622007-08-15 14:28:22 +00001129
1130.. function:: getLevelName(lvl)
1131
1132 Returns the textual representation of logging level *lvl*. If the level is one
1133 of the predefined levels :const:`CRITICAL`, :const:`ERROR`, :const:`WARNING`,
1134 :const:`INFO` or :const:`DEBUG` then you get the corresponding string. If you
1135 have associated levels with names using :func:`addLevelName` then the name you
1136 have associated with *lvl* is returned. If a numeric value corresponding to one
1137 of the defined levels is passed in, the corresponding string representation is
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001138 returned. Otherwise, the string 'Level %s' % lvl is returned.
Georg Brandl116aa622007-08-15 14:28:22 +00001139
1140
1141.. function:: makeLogRecord(attrdict)
1142
1143 Creates and returns a new :class:`LogRecord` instance whose attributes are
1144 defined by *attrdict*. This function is useful for taking a pickled
1145 :class:`LogRecord` attribute dictionary, sent over a socket, and reconstituting
1146 it as a :class:`LogRecord` instance at the receiving end.
1147
1148
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001149.. function:: basicConfig(**kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001150
1151 Does basic configuration for the logging system by creating a
1152 :class:`StreamHandler` with a default :class:`Formatter` and adding it to the
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00001153 root logger. The functions :func:`debug`, :func:`info`, :func:`warning`,
Georg Brandl116aa622007-08-15 14:28:22 +00001154 :func:`error` and :func:`critical` will call :func:`basicConfig` automatically
1155 if no handlers are defined for the root logger.
1156
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00001157 This function does nothing if the root logger already has handlers
1158 configured for it.
1159
Vinay Sajipc8c8c692010-09-17 10:09:04 +00001160 PLEASE NOTE: This function should be called from the main thread
1161 before other threads are started. In versions of Python prior to
1162 2.7.1 and 3.2, if this function is called from multiple threads,
1163 it is possible (in rare circumstances) that a handler will be added
1164 to the root logger more than once, leading to unexpected results
1165 such as messages being duplicated in the log.
1166
Georg Brandl116aa622007-08-15 14:28:22 +00001167 The following keyword arguments are supported.
1168
1169 +--------------+---------------------------------------------+
1170 | Format | Description |
1171 +==============+=============================================+
1172 | ``filename`` | Specifies that a FileHandler be created, |
1173 | | using the specified filename, rather than a |
1174 | | StreamHandler. |
1175 +--------------+---------------------------------------------+
1176 | ``filemode`` | Specifies the mode to open the file, if |
1177 | | filename is specified (if filemode is |
1178 | | unspecified, it defaults to 'a'). |
1179 +--------------+---------------------------------------------+
1180 | ``format`` | Use the specified format string for the |
1181 | | handler. |
1182 +--------------+---------------------------------------------+
1183 | ``datefmt`` | Use the specified date/time format. |
1184 +--------------+---------------------------------------------+
Vinay Sajipc5b27302010-10-31 14:59:16 +00001185 | ``style`` | If ``format`` is specified, use this style |
1186 | | for the format string. One of '%', '{' or |
1187 | | '$' for %-formatting, :meth:`str.format` or |
1188 | | :class:`string.Template` respectively, and |
1189 | | defaulting to '%' if not specified. |
1190 +--------------+---------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001191 | ``level`` | Set the root logger level to the specified |
1192 | | level. |
1193 +--------------+---------------------------------------------+
1194 | ``stream`` | Use the specified stream to initialize the |
1195 | | StreamHandler. Note that this argument is |
1196 | | incompatible with 'filename' - if both are |
1197 | | present, 'stream' is ignored. |
1198 +--------------+---------------------------------------------+
1199
Vinay Sajipc5b27302010-10-31 14:59:16 +00001200 .. versionchanged:: 3.2
1201 The ``style`` argument was added.
1202
1203
Georg Brandl116aa622007-08-15 14:28:22 +00001204.. function:: shutdown()
1205
1206 Informs the logging system to perform an orderly shutdown by flushing and
Christian Heimesb186d002008-03-18 15:15:01 +00001207 closing all handlers. This should be called at application exit and no
1208 further use of the logging system should be made after this call.
Georg Brandl116aa622007-08-15 14:28:22 +00001209
1210
1211.. function:: setLoggerClass(klass)
1212
1213 Tells the logging system to use the class *klass* when instantiating a logger.
1214 The class should define :meth:`__init__` such that only a name argument is
1215 required, and the :meth:`__init__` should call :meth:`Logger.__init__`. This
1216 function is typically called before any loggers are instantiated by applications
1217 which need to use custom logger behavior.
1218
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001219
Vinay Sajip61561522010-12-03 11:50:38 +00001220.. function:: setLogRecordFactory(factory)
1221
1222 Set a callable which is used to create a :class:`LogRecord`.
1223
1224 :param factory: The factory callable to be used to instantiate a log record.
1225
1226 .. versionadded:: 3.2
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001227 This function has been provided, along with :func:`getLogRecordFactory`, to
1228 allow developers more control over how the :class:`LogRecord` representing
1229 a logging event is constructed.
Vinay Sajip61561522010-12-03 11:50:38 +00001230
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001231 The factory has the following signature:
Vinay Sajip61561522010-12-03 11:50:38 +00001232
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001233 ``factory(name, level, fn, lno, msg, args, exc_info, func=None, sinfo=None, **kwargs)``
Vinay Sajip61561522010-12-03 11:50:38 +00001234
1235 :name: The logger name.
1236 :level: The logging level (numeric).
1237 :fn: The full pathname of the file where the logging call was made.
1238 :lno: The line number in the file where the logging call was made.
1239 :msg: The logging message.
1240 :args: The arguments for the logging message.
1241 :exc_info: An exception tuple, or None.
1242 :func: The name of the function or method which invoked the logging
1243 call.
1244 :sinfo: A stack traceback such as is provided by
1245 :func:`traceback.print_stack`, showing the call hierarchy.
1246 :kwargs: Additional keyword arguments.
Georg Brandl116aa622007-08-15 14:28:22 +00001247
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001248
Georg Brandl116aa622007-08-15 14:28:22 +00001249.. seealso::
1250
1251 :pep:`282` - A Logging System
1252 The proposal which described this feature for inclusion in the Python standard
1253 library.
1254
Christian Heimes255f53b2007-12-08 15:33:56 +00001255 `Original Python logging package <http://www.red-dove.com/python_logging.html>`_
Georg Brandl116aa622007-08-15 14:28:22 +00001256 This is the original source for the :mod:`logging` package. The version of the
1257 package available from this site is suitable for use with Python 1.5.2, 2.1.x
1258 and 2.2.x, which do not include the :mod:`logging` package in the standard
1259 library.
1260
Vinay Sajip4039aff2010-09-11 10:25:28 +00001261.. _logger:
Georg Brandl116aa622007-08-15 14:28:22 +00001262
1263Logger Objects
1264--------------
1265
1266Loggers have the following attributes and methods. Note that Loggers are never
1267instantiated directly, but always through the module-level function
1268``logging.getLogger(name)``.
1269
Vinay Sajip0258ce82010-09-22 20:34:53 +00001270.. class:: Logger
Georg Brandl116aa622007-08-15 14:28:22 +00001271
1272.. attribute:: Logger.propagate
1273
1274 If this evaluates to false, logging messages are not passed by this logger or by
Benjamin Peterson22005fc2010-04-11 16:25:06 +00001275 its child loggers to the handlers of higher level (ancestor) loggers. The
1276 constructor sets this attribute to 1.
Georg Brandl116aa622007-08-15 14:28:22 +00001277
1278
1279.. method:: Logger.setLevel(lvl)
1280
1281 Sets the threshold for this logger to *lvl*. Logging messages which are less
1282 severe than *lvl* will be ignored. When a logger is created, the level is set to
1283 :const:`NOTSET` (which causes all messages to be processed when the logger is
1284 the root logger, or delegation to the parent when the logger is a non-root
1285 logger). Note that the root logger is created with level :const:`WARNING`.
1286
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001287 The term 'delegation to the parent' means that if a logger has a level of
Georg Brandl116aa622007-08-15 14:28:22 +00001288 NOTSET, its chain of ancestor loggers is traversed until either an ancestor with
1289 a level other than NOTSET is found, or the root is reached.
1290
1291 If an ancestor is found with a level other than NOTSET, then that ancestor's
1292 level is treated as the effective level of the logger where the ancestor search
1293 began, and is used to determine how a logging event is handled.
1294
1295 If the root is reached, and it has a level of NOTSET, then all messages will be
1296 processed. Otherwise, the root's level will be used as the effective level.
1297
1298
1299.. method:: Logger.isEnabledFor(lvl)
1300
1301 Indicates if a message of severity *lvl* would be processed by this logger.
1302 This method checks first the module-level level set by
1303 ``logging.disable(lvl)`` and then the logger's effective level as determined
1304 by :meth:`getEffectiveLevel`.
1305
1306
1307.. method:: Logger.getEffectiveLevel()
1308
1309 Indicates the effective level for this logger. If a value other than
1310 :const:`NOTSET` has been set using :meth:`setLevel`, it is returned. Otherwise,
1311 the hierarchy is traversed towards the root until a value other than
1312 :const:`NOTSET` is found, and that value is returned.
1313
1314
Benjamin Peterson22005fc2010-04-11 16:25:06 +00001315.. method:: Logger.getChild(suffix)
1316
1317 Returns a logger which is a descendant to this logger, as determined by the suffix.
1318 Thus, ``logging.getLogger('abc').getChild('def.ghi')`` would return the same
1319 logger as would be returned by ``logging.getLogger('abc.def.ghi')``. This is a
1320 convenience method, useful when the parent logger is named using e.g. ``__name__``
1321 rather than a literal string.
1322
1323 .. versionadded:: 3.2
1324
Georg Brandl67b21b72010-08-17 15:07:14 +00001325
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001326.. method:: Logger.debug(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001327
1328 Logs a message with level :const:`DEBUG` on this logger. The *msg* is the
1329 message format string, and the *args* are the arguments which are merged into
1330 *msg* using the string formatting operator. (Note that this means that you can
1331 use keywords in the format string, together with a single dictionary argument.)
1332
Vinay Sajip8593ae62010-11-14 21:33:04 +00001333 There are three keyword arguments in *kwargs* which are inspected: *exc_info*
Georg Brandl116aa622007-08-15 14:28:22 +00001334 which, if it does not evaluate as false, causes exception information to be
1335 added to the logging message. If an exception tuple (in the format returned by
1336 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
1337 is called to get the exception information.
1338
Vinay Sajip8593ae62010-11-14 21:33:04 +00001339 The second optional keyword argument is *stack_info*, which defaults to
1340 False. If specified as True, stack information is added to the logging
1341 message, including the actual logging call. Note that this is not the same
1342 stack information as that displayed through specifying *exc_info*: The
1343 former is stack frames from the bottom of the stack up to the logging call
1344 in the current thread, whereas the latter is information about stack frames
1345 which have been unwound, following an exception, while searching for
1346 exception handlers.
1347
1348 You can specify *stack_info* independently of *exc_info*, e.g. to just show
1349 how you got to a certain point in your code, even when no exceptions were
1350 raised. The stack frames are printed following a header line which says::
1351
1352 Stack (most recent call last):
1353
1354 This mimics the `Traceback (most recent call last):` which is used when
1355 displaying exception frames.
1356
1357 The third keyword argument is *extra* which can be used to pass a
Georg Brandl116aa622007-08-15 14:28:22 +00001358 dictionary which is used to populate the __dict__ of the LogRecord created for
1359 the logging event with user-defined attributes. These custom attributes can then
1360 be used as you like. For example, they could be incorporated into logged
1361 messages. For example::
1362
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001363 FORMAT = '%(asctime)-15s %(clientip)s %(user)-8s %(message)s'
Georg Brandl116aa622007-08-15 14:28:22 +00001364 logging.basicConfig(format=FORMAT)
Georg Brandl9afde1c2007-11-01 20:32:30 +00001365 d = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001366 logger = logging.getLogger('tcpserver')
1367 logger.warning('Protocol problem: %s', 'connection reset', extra=d)
Georg Brandl116aa622007-08-15 14:28:22 +00001368
1369 would print something like ::
1370
1371 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
1372
1373 The keys in the dictionary passed in *extra* should not clash with the keys used
1374 by the logging system. (See the :class:`Formatter` documentation for more
1375 information on which keys are used by the logging system.)
1376
1377 If you choose to use these attributes in logged messages, you need to exercise
1378 some care. In the above example, for instance, the :class:`Formatter` has been
1379 set up with a format string which expects 'clientip' and 'user' in the attribute
1380 dictionary of the LogRecord. If these are missing, the message will not be
1381 logged because a string formatting exception will occur. So in this case, you
1382 always need to pass the *extra* dictionary with these keys.
1383
1384 While this might be annoying, this feature is intended for use in specialized
1385 circumstances, such as multi-threaded servers where the same code executes in
1386 many contexts, and interesting conditions which arise are dependent on this
1387 context (such as remote client IP address and authenticated user name, in the
1388 above example). In such circumstances, it is likely that specialized
1389 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
1390
Vinay Sajip8593ae62010-11-14 21:33:04 +00001391 .. versionadded:: 3.2
1392 The *stack_info* parameter was added.
1393
Georg Brandl116aa622007-08-15 14:28:22 +00001394
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001395.. method:: Logger.info(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001396
1397 Logs a message with level :const:`INFO` on this logger. The arguments are
1398 interpreted as for :meth:`debug`.
1399
1400
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001401.. method:: Logger.warning(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001402
1403 Logs a message with level :const:`WARNING` on this logger. The arguments are
1404 interpreted as for :meth:`debug`.
1405
1406
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001407.. method:: Logger.error(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001408
1409 Logs a message with level :const:`ERROR` on this logger. The arguments are
1410 interpreted as for :meth:`debug`.
1411
1412
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001413.. method:: Logger.critical(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001414
1415 Logs a message with level :const:`CRITICAL` on this logger. The arguments are
1416 interpreted as for :meth:`debug`.
1417
1418
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001419.. method:: Logger.log(lvl, msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001420
1421 Logs a message with integer level *lvl* on this logger. The other arguments are
1422 interpreted as for :meth:`debug`.
1423
1424
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001425.. method:: Logger.exception(msg, *args)
Georg Brandl116aa622007-08-15 14:28:22 +00001426
1427 Logs a message with level :const:`ERROR` on this logger. The arguments are
1428 interpreted as for :meth:`debug`. Exception info is added to the logging
1429 message. This method should only be called from an exception handler.
1430
1431
1432.. method:: Logger.addFilter(filt)
1433
1434 Adds the specified filter *filt* to this logger.
1435
1436
1437.. method:: Logger.removeFilter(filt)
1438
1439 Removes the specified filter *filt* from this logger.
1440
1441
1442.. method:: Logger.filter(record)
1443
1444 Applies this logger's filters to the record and returns a true value if the
1445 record is to be processed.
1446
1447
1448.. method:: Logger.addHandler(hdlr)
1449
1450 Adds the specified handler *hdlr* to this logger.
1451
1452
1453.. method:: Logger.removeHandler(hdlr)
1454
1455 Removes the specified handler *hdlr* from this logger.
1456
1457
Vinay Sajip8593ae62010-11-14 21:33:04 +00001458.. method:: Logger.findCaller(stack_info=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001459
1460 Finds the caller's source filename and line number. Returns the filename, line
Vinay Sajip8593ae62010-11-14 21:33:04 +00001461 number, function name and stack information as a 4-element tuple. The stack
1462 information is returned as *None* unless *stack_info* is *True*.
Georg Brandl116aa622007-08-15 14:28:22 +00001463
Georg Brandl116aa622007-08-15 14:28:22 +00001464
1465.. method:: Logger.handle(record)
1466
1467 Handles a record by passing it to all handlers associated with this logger and
1468 its ancestors (until a false value of *propagate* is found). This method is used
1469 for unpickled records received from a socket, as well as those created locally.
Georg Brandl502d9a52009-07-26 15:02:41 +00001470 Logger-level filtering is applied using :meth:`~Logger.filter`.
Georg Brandl116aa622007-08-15 14:28:22 +00001471
1472
Vinay Sajip8593ae62010-11-14 21:33:04 +00001473.. method:: Logger.makeRecord(name, lvl, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001474
1475 This is a factory method which can be overridden in subclasses to create
1476 specialized :class:`LogRecord` instances.
1477
Vinay Sajip83eadd12010-09-20 10:31:18 +00001478.. method:: Logger.hasHandlers()
1479
1480 Checks to see if this logger has any handlers configured. This is done by
1481 looking for handlers in this logger and its parents in the logger hierarchy.
1482 Returns True if a handler was found, else False. The method stops searching
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001483 up the hierarchy whenever a logger with the 'propagate' attribute set to
Vinay Sajip83eadd12010-09-20 10:31:18 +00001484 False is found - that will be the last logger which is checked for the
1485 existence of handlers.
1486
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001487 .. versionadded:: 3.2
Vinay Sajip83eadd12010-09-20 10:31:18 +00001488
Vinay Sajipa18b9592010-12-12 13:20:55 +00001489.. _basic-example:
Georg Brandl116aa622007-08-15 14:28:22 +00001490
1491Basic example
1492-------------
1493
Georg Brandl116aa622007-08-15 14:28:22 +00001494The :mod:`logging` package provides a lot of flexibility, and its configuration
1495can appear daunting. This section demonstrates that simple use of the logging
1496package is possible.
1497
1498The simplest example shows logging to the console::
1499
1500 import logging
1501
1502 logging.debug('A debug message')
1503 logging.info('Some information')
1504 logging.warning('A shot across the bows')
1505
1506If you run the above script, you'll see this::
1507
1508 WARNING:root:A shot across the bows
1509
1510Because no particular logger was specified, the system used the root logger. The
1511debug and info messages didn't appear because by default, the root logger is
1512configured to only handle messages with a severity of WARNING or above. The
1513message format is also a configuration default, as is the output destination of
1514the messages - ``sys.stderr``. The severity level, the message format and
1515destination can be easily changed, as shown in the example below::
1516
1517 import logging
1518
1519 logging.basicConfig(level=logging.DEBUG,
1520 format='%(asctime)s %(levelname)s %(message)s',
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001521 filename='myapp.log',
Georg Brandl116aa622007-08-15 14:28:22 +00001522 filemode='w')
1523 logging.debug('A debug message')
1524 logging.info('Some information')
1525 logging.warning('A shot across the bows')
1526
1527The :meth:`basicConfig` method is used to change the configuration defaults,
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001528which results in output (written to ``myapp.log``) which should look
Georg Brandl116aa622007-08-15 14:28:22 +00001529something like the following::
1530
1531 2004-07-02 13:00:08,743 DEBUG A debug message
1532 2004-07-02 13:00:08,743 INFO Some information
1533 2004-07-02 13:00:08,743 WARNING A shot across the bows
1534
1535This time, all messages with a severity of DEBUG or above were handled, and the
1536format of the messages was also changed, and output went to the specified file
1537rather than the console.
1538
Georg Brandl81ac1ce2007-08-31 17:17:17 +00001539.. XXX logging should probably be updated for new string formatting!
Georg Brandl4b491312007-08-31 09:22:56 +00001540
1541Formatting uses the old Python string formatting - see section
1542:ref:`old-string-formatting`. The format string takes the following common
Georg Brandl116aa622007-08-15 14:28:22 +00001543specifiers. For a complete list of specifiers, consult the :class:`Formatter`
1544documentation.
1545
1546+-------------------+-----------------------------------------------+
1547| Format | Description |
1548+===================+===============================================+
1549| ``%(name)s`` | Name of the logger (logging channel). |
1550+-------------------+-----------------------------------------------+
1551| ``%(levelname)s`` | Text logging level for the message |
1552| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
1553| | ``'ERROR'``, ``'CRITICAL'``). |
1554+-------------------+-----------------------------------------------+
1555| ``%(asctime)s`` | Human-readable time when the |
1556| | :class:`LogRecord` was created. By default |
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001557| | this is of the form '2003-07-08 16:49:45,896' |
Georg Brandl116aa622007-08-15 14:28:22 +00001558| | (the numbers after the comma are millisecond |
1559| | portion of the time). |
1560+-------------------+-----------------------------------------------+
1561| ``%(message)s`` | The logged message. |
1562+-------------------+-----------------------------------------------+
1563
1564To change the date/time format, you can pass an additional keyword parameter,
1565*datefmt*, as in the following::
1566
1567 import logging
1568
1569 logging.basicConfig(level=logging.DEBUG,
1570 format='%(asctime)s %(levelname)-8s %(message)s',
1571 datefmt='%a, %d %b %Y %H:%M:%S',
1572 filename='/temp/myapp.log',
1573 filemode='w')
1574 logging.debug('A debug message')
1575 logging.info('Some information')
1576 logging.warning('A shot across the bows')
1577
1578which would result in output like ::
1579
1580 Fri, 02 Jul 2004 13:06:18 DEBUG A debug message
1581 Fri, 02 Jul 2004 13:06:18 INFO Some information
1582 Fri, 02 Jul 2004 13:06:18 WARNING A shot across the bows
1583
1584The date format string follows the requirements of :func:`strftime` - see the
1585documentation for the :mod:`time` module.
1586
1587If, instead of sending logging output to the console or a file, you'd rather use
1588a file-like object which you have created separately, you can pass it to
1589:func:`basicConfig` using the *stream* keyword argument. Note that if both
1590*stream* and *filename* keyword arguments are passed, the *stream* argument is
1591ignored.
1592
1593Of course, you can put variable information in your output. To do this, simply
1594have the message be a format string and pass in additional arguments containing
1595the variable information, as in the following example::
1596
1597 import logging
1598
1599 logging.basicConfig(level=logging.DEBUG,
1600 format='%(asctime)s %(levelname)-8s %(message)s',
1601 datefmt='%a, %d %b %Y %H:%M:%S',
1602 filename='/temp/myapp.log',
1603 filemode='w')
1604 logging.error('Pack my box with %d dozen %s', 5, 'liquor jugs')
1605
1606which would result in ::
1607
1608 Wed, 21 Jul 2004 15:35:16 ERROR Pack my box with 5 dozen liquor jugs
1609
1610
Vinay Sajipa18b9592010-12-12 13:20:55 +00001611Using file rotation
1612^^^^^^^^^^^^^^^^^^^
1613
1614.. sectionauthor:: Doug Hellmann, Vinay Sajip (changes)
1615.. (see <http://blog.doughellmann.com/2007/05/pymotw-logging.html>)
1616
1617Sometimes you want to let a log file grow to a certain size, then open a new
1618file and log to that. You may want to keep a certain number of these files, and
1619when that many files have been created, rotate the files so that the number of
1620files and the size of the files both remin bounded. For this usage pattern, the
1621logging package provides a :class:`RotatingFileHandler`::
1622
1623 import glob
1624 import logging
1625 import logging.handlers
1626
1627 LOG_FILENAME = 'logging_rotatingfile_example.out'
1628
1629 # Set up a specific logger with our desired output level
1630 my_logger = logging.getLogger('MyLogger')
1631 my_logger.setLevel(logging.DEBUG)
1632
1633 # Add the log message handler to the logger
1634 handler = logging.handlers.RotatingFileHandler(
1635 LOG_FILENAME, maxBytes=20, backupCount=5)
1636
1637 my_logger.addHandler(handler)
1638
1639 # Log some messages
1640 for i in range(20):
1641 my_logger.debug('i = %d' % i)
1642
1643 # See what files are created
1644 logfiles = glob.glob('%s*' % LOG_FILENAME)
1645
1646 for filename in logfiles:
1647 print(filename)
1648
1649The result should be 6 separate files, each with part of the log history for the
1650application::
1651
1652 logging_rotatingfile_example.out
1653 logging_rotatingfile_example.out.1
1654 logging_rotatingfile_example.out.2
1655 logging_rotatingfile_example.out.3
1656 logging_rotatingfile_example.out.4
1657 logging_rotatingfile_example.out.5
1658
1659The most current file is always :file:`logging_rotatingfile_example.out`,
1660and each time it reaches the size limit it is renamed with the suffix
1661``.1``. Each of the existing backup files is renamed to increment the suffix
1662(``.1`` becomes ``.2``, etc.) and the ``.6`` file is erased.
1663
1664Obviously this example sets the log length much much too small as an extreme
1665example. You would want to set *maxBytes* to an appropriate value.
1666
1667
1668The logger, handler, and log message call each specify a level. The log message
1669is only emitted if the handler and logger are configured to emit messages of
1670that level or lower. For example, if a message is ``CRITICAL``, and the logger
1671is set to ``ERROR``, the message is emitted. If a message is a ``WARNING``, and
1672the logger is set to produce only ``ERROR``\s, the message is not emitted::
1673
1674 import logging
1675 import sys
1676
1677 LEVELS = {'debug': logging.DEBUG,
1678 'info': logging.INFO,
1679 'warning': logging.WARNING,
1680 'error': logging.ERROR,
1681 'critical': logging.CRITICAL}
1682
1683 if len(sys.argv) > 1:
1684 level_name = sys.argv[1]
1685 level = LEVELS.get(level_name, logging.NOTSET)
1686 logging.basicConfig(level=level)
1687
1688 logging.debug('This is a debug message')
1689 logging.info('This is an info message')
1690 logging.warning('This is a warning message')
1691 logging.error('This is an error message')
1692 logging.critical('This is a critical error message')
1693
1694Run the script with an argument like 'debug' or 'warning' to see which messages
1695show up at different levels::
1696
1697 $ python logging_level_example.py debug
1698 DEBUG:root:This is a debug message
1699 INFO:root:This is an info message
1700 WARNING:root:This is a warning message
1701 ERROR:root:This is an error message
1702 CRITICAL:root:This is a critical error message
1703
1704 $ python logging_level_example.py info
1705 INFO:root:This is an info message
1706 WARNING:root:This is a warning message
1707 ERROR:root:This is an error message
1708 CRITICAL:root:This is a critical error message
1709
1710You will notice that these log messages all have ``root`` embedded in them. The
1711logging module supports a hierarchy of loggers with different names. An easy
1712way to tell where a specific log message comes from is to use a separate logger
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001713object for each of your modules. Each new logger 'inherits' the configuration
Vinay Sajipa18b9592010-12-12 13:20:55 +00001714of its parent, and log messages sent to a logger include the name of that
1715logger. Optionally, each logger can be configured differently, so that messages
1716from different modules are handled in different ways. Let's look at a simple
1717example of how to log from different modules so it is easy to trace the source
1718of the message::
1719
1720 import logging
1721
1722 logging.basicConfig(level=logging.WARNING)
1723
1724 logger1 = logging.getLogger('package1.module1')
1725 logger2 = logging.getLogger('package2.module2')
1726
1727 logger1.warning('This message comes from one module')
1728 logger2.warning('And this message comes from another module')
1729
1730And the output::
1731
1732 $ python logging_modules_example.py
1733 WARNING:package1.module1:This message comes from one module
1734 WARNING:package2.module2:And this message comes from another module
1735
1736There are many more options for configuring logging, including different log
1737message formatting options, having messages delivered to multiple destinations,
1738and changing the configuration of a long-running application on the fly using a
1739socket interface. All of these options are covered in depth in the library
1740module documentation.
1741
1742
Georg Brandl116aa622007-08-15 14:28:22 +00001743.. _multiple-destinations:
1744
1745Logging to multiple destinations
1746--------------------------------
1747
1748Let's say you want to log to console and file with different message formats and
1749in differing circumstances. Say you want to log messages with levels of DEBUG
1750and higher to file, and those messages at level INFO and higher to the console.
1751Let's also assume that the file should contain timestamps, but the console
1752messages should not. Here's how you can achieve this::
1753
1754 import logging
1755
1756 # set up logging to file - see previous section for more details
1757 logging.basicConfig(level=logging.DEBUG,
1758 format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
1759 datefmt='%m-%d %H:%M',
1760 filename='/temp/myapp.log',
1761 filemode='w')
1762 # define a Handler which writes INFO messages or higher to the sys.stderr
1763 console = logging.StreamHandler()
1764 console.setLevel(logging.INFO)
1765 # set a format which is simpler for console use
1766 formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
1767 # tell the handler to use this format
1768 console.setFormatter(formatter)
1769 # add the handler to the root logger
1770 logging.getLogger('').addHandler(console)
1771
1772 # Now, we can log to the root logger, or any other logger. First the root...
1773 logging.info('Jackdaws love my big sphinx of quartz.')
1774
1775 # Now, define a couple of other loggers which might represent areas in your
1776 # application:
1777
1778 logger1 = logging.getLogger('myapp.area1')
1779 logger2 = logging.getLogger('myapp.area2')
1780
1781 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
1782 logger1.info('How quickly daft jumping zebras vex.')
1783 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
1784 logger2.error('The five boxing wizards jump quickly.')
1785
1786When you run this, on the console you will see ::
1787
1788 root : INFO Jackdaws love my big sphinx of quartz.
1789 myapp.area1 : INFO How quickly daft jumping zebras vex.
1790 myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.
1791 myapp.area2 : ERROR The five boxing wizards jump quickly.
1792
1793and in the file you will see something like ::
1794
1795 10-22 22:19 root INFO Jackdaws love my big sphinx of quartz.
1796 10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
1797 10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.
1798 10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
1799 10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.
1800
1801As you can see, the DEBUG message only shows up in the file. The other messages
1802are sent to both destinations.
1803
1804This example uses console and file handlers, but you can use any number and
1805combination of handlers you choose.
1806
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001807.. _logging-exceptions:
1808
1809Exceptions raised during logging
1810--------------------------------
1811
1812The logging package is designed to swallow exceptions which occur while logging
1813in production. This is so that errors which occur while handling logging events
1814- such as logging misconfiguration, network or other similar errors - do not
1815cause the application using logging to terminate prematurely.
1816
1817:class:`SystemExit` and :class:`KeyboardInterrupt` exceptions are never
1818swallowed. Other exceptions which occur during the :meth:`emit` method of a
1819:class:`Handler` subclass are passed to its :meth:`handleError` method.
1820
1821The default implementation of :meth:`handleError` in :class:`Handler` checks
Georg Brandlef871f62010-03-12 10:06:40 +00001822to see if a module-level variable, :data:`raiseExceptions`, is set. If set, a
1823traceback is printed to :data:`sys.stderr`. If not set, the exception is swallowed.
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001824
Georg Brandlef871f62010-03-12 10:06:40 +00001825**Note:** The default value of :data:`raiseExceptions` is ``True``. This is because
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001826during development, you typically want to be notified of any exceptions that
Georg Brandlef871f62010-03-12 10:06:40 +00001827occur. It's advised that you set :data:`raiseExceptions` to ``False`` for production
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001828usage.
Georg Brandl116aa622007-08-15 14:28:22 +00001829
Christian Heimes790c8232008-01-07 21:14:23 +00001830.. _context-info:
1831
1832Adding contextual information to your logging output
1833----------------------------------------------------
1834
1835Sometimes you want logging output to contain contextual information in
1836addition to the parameters passed to the logging call. For example, in a
1837networked application, it may be desirable to log client-specific information
1838in the log (e.g. remote client's username, or IP address). Although you could
1839use the *extra* parameter to achieve this, it's not always convenient to pass
1840the information in this way. While it might be tempting to create
1841:class:`Logger` instances on a per-connection basis, this is not a good idea
1842because these instances are not garbage collected. While this is not a problem
1843in practice, when the number of :class:`Logger` instances is dependent on the
1844level of granularity you want to use in logging an application, it could
1845be hard to manage if the number of :class:`Logger` instances becomes
1846effectively unbounded.
1847
Vinay Sajipc31be632010-09-06 22:18:20 +00001848
1849Using LoggerAdapters to impart contextual information
1850^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1851
Christian Heimes04c420f2008-01-18 18:40:46 +00001852An easy way in which you can pass contextual information to be output along
1853with logging event information is to use the :class:`LoggerAdapter` class.
1854This class is designed to look like a :class:`Logger`, so that you can call
1855:meth:`debug`, :meth:`info`, :meth:`warning`, :meth:`error`,
1856:meth:`exception`, :meth:`critical` and :meth:`log`. These methods have the
1857same signatures as their counterparts in :class:`Logger`, so you can use the
1858two types of instances interchangeably.
Christian Heimes790c8232008-01-07 21:14:23 +00001859
Christian Heimes04c420f2008-01-18 18:40:46 +00001860When you create an instance of :class:`LoggerAdapter`, you pass it a
1861:class:`Logger` instance and a dict-like object which contains your contextual
1862information. When you call one of the logging methods on an instance of
1863:class:`LoggerAdapter`, it delegates the call to the underlying instance of
1864:class:`Logger` passed to its constructor, and arranges to pass the contextual
1865information in the delegated call. Here's a snippet from the code of
1866:class:`LoggerAdapter`::
Christian Heimes790c8232008-01-07 21:14:23 +00001867
Christian Heimes04c420f2008-01-18 18:40:46 +00001868 def debug(self, msg, *args, **kwargs):
1869 """
1870 Delegate a debug call to the underlying logger, after adding
1871 contextual information from this adapter instance.
1872 """
1873 msg, kwargs = self.process(msg, kwargs)
1874 self.logger.debug(msg, *args, **kwargs)
Christian Heimes790c8232008-01-07 21:14:23 +00001875
Christian Heimes04c420f2008-01-18 18:40:46 +00001876The :meth:`process` method of :class:`LoggerAdapter` is where the contextual
1877information is added to the logging output. It's passed the message and
1878keyword arguments of the logging call, and it passes back (potentially)
1879modified versions of these to use in the call to the underlying logger. The
1880default implementation of this method leaves the message alone, but inserts
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001881an 'extra' key in the keyword argument whose value is the dict-like object
1882passed to the constructor. Of course, if you had passed an 'extra' keyword
Christian Heimes04c420f2008-01-18 18:40:46 +00001883argument in the call to the adapter, it will be silently overwritten.
Christian Heimes790c8232008-01-07 21:14:23 +00001884
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001885The advantage of using 'extra' is that the values in the dict-like object are
Christian Heimes04c420f2008-01-18 18:40:46 +00001886merged into the :class:`LogRecord` instance's __dict__, allowing you to use
1887customized strings with your :class:`Formatter` instances which know about
1888the keys of the dict-like object. If you need a different method, e.g. if you
1889want to prepend or append the contextual information to the message string,
1890you just need to subclass :class:`LoggerAdapter` and override :meth:`process`
1891to do what you need. Here's an example script which uses this class, which
1892also illustrates what dict-like behaviour is needed from an arbitrary
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001893'dict-like' object for use in the constructor::
Christian Heimes04c420f2008-01-18 18:40:46 +00001894
Christian Heimes587c2bf2008-01-19 16:21:02 +00001895 import logging
Georg Brandl86def6c2008-01-21 20:36:10 +00001896
Christian Heimes587c2bf2008-01-19 16:21:02 +00001897 class ConnInfo:
1898 """
1899 An example class which shows how an arbitrary class can be used as
1900 the 'extra' context information repository passed to a LoggerAdapter.
1901 """
Georg Brandl86def6c2008-01-21 20:36:10 +00001902
Christian Heimes587c2bf2008-01-19 16:21:02 +00001903 def __getitem__(self, name):
1904 """
1905 To allow this instance to look like a dict.
1906 """
1907 from random import choice
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001908 if name == 'ip':
1909 result = choice(['127.0.0.1', '192.168.0.1'])
1910 elif name == 'user':
1911 result = choice(['jim', 'fred', 'sheila'])
Christian Heimes587c2bf2008-01-19 16:21:02 +00001912 else:
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001913 result = self.__dict__.get(name, '?')
Christian Heimes587c2bf2008-01-19 16:21:02 +00001914 return result
Georg Brandl86def6c2008-01-21 20:36:10 +00001915
Christian Heimes587c2bf2008-01-19 16:21:02 +00001916 def __iter__(self):
1917 """
1918 To allow iteration over keys, which will be merged into
1919 the LogRecord dict before formatting and output.
1920 """
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001921 keys = ['ip', 'user']
Christian Heimes587c2bf2008-01-19 16:21:02 +00001922 keys.extend(self.__dict__.keys())
1923 return keys.__iter__()
Georg Brandl86def6c2008-01-21 20:36:10 +00001924
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001925 if __name__ == '__main__':
Christian Heimes587c2bf2008-01-19 16:21:02 +00001926 from random import choice
1927 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001928 a1 = logging.LoggerAdapter(logging.getLogger('a.b.c'),
1929 { 'ip' : '123.231.231.123', 'user' : 'sheila' })
Christian Heimes587c2bf2008-01-19 16:21:02 +00001930 logging.basicConfig(level=logging.DEBUG,
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001931 format='%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s')
1932 a1.debug('A debug message')
1933 a1.info('An info message with %s', 'some parameters')
1934 a2 = logging.LoggerAdapter(logging.getLogger('d.e.f'), ConnInfo())
Christian Heimes587c2bf2008-01-19 16:21:02 +00001935 for x in range(10):
1936 lvl = choice(levels)
1937 lvlname = logging.getLevelName(lvl)
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001938 a2.log(lvl, 'A message at %s level with %d %s', lvlname, 2, 'parameters')
Christian Heimes04c420f2008-01-18 18:40:46 +00001939
1940When this script is run, the output should look something like this::
1941
Christian Heimes587c2bf2008-01-19 16:21:02 +00001942 2008-01-18 14:49:54,023 a.b.c DEBUG IP: 123.231.231.123 User: sheila A debug message
1943 2008-01-18 14:49:54,023 a.b.c INFO IP: 123.231.231.123 User: sheila An info message with some parameters
1944 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
1945 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
1946 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
1947 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
1948 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
1949 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
1950 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
1951 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
1952 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
1953 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 +00001954
Christian Heimes790c8232008-01-07 21:14:23 +00001955
Vinay Sajipac007992010-09-17 12:45:26 +00001956.. _filters-contextual:
1957
Vinay Sajipc31be632010-09-06 22:18:20 +00001958Using Filters to impart contextual information
1959^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1960
1961You can also add contextual information to log output using a user-defined
1962:class:`Filter`. ``Filter`` instances are allowed to modify the ``LogRecords``
1963passed to them, including adding additional attributes which can then be output
1964using a suitable format string, or if needed a custom :class:`Formatter`.
1965
1966For example in a web application, the request being processed (or at least,
1967the interesting parts of it) can be stored in a threadlocal
1968(:class:`threading.local`) variable, and then accessed from a ``Filter`` to
1969add, say, information from the request - say, the remote IP address and remote
1970user's username - to the ``LogRecord``, using the attribute names 'ip' and
1971'user' as in the ``LoggerAdapter`` example above. In that case, the same format
1972string can be used to get similar output to that shown above. Here's an example
1973script::
1974
1975 import logging
1976 from random import choice
1977
1978 class ContextFilter(logging.Filter):
1979 """
1980 This is a filter which injects contextual information into the log.
1981
1982 Rather than use actual contextual information, we just use random
1983 data in this demo.
1984 """
1985
1986 USERS = ['jim', 'fred', 'sheila']
1987 IPS = ['123.231.231.123', '127.0.0.1', '192.168.0.1']
1988
1989 def filter(self, record):
1990
1991 record.ip = choice(ContextFilter.IPS)
1992 record.user = choice(ContextFilter.USERS)
1993 return True
1994
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001995 if __name__ == '__main__':
Vinay Sajipc31be632010-09-06 22:18:20 +00001996 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001997 a1 = logging.LoggerAdapter(logging.getLogger('a.b.c'),
1998 { 'ip' : '123.231.231.123', 'user' : 'sheila' })
Vinay Sajipc31be632010-09-06 22:18:20 +00001999 logging.basicConfig(level=logging.DEBUG,
Vinay Sajip9a6b4002010-12-14 19:40:21 +00002000 format='%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s')
2001 a1 = logging.getLogger('a.b.c')
2002 a2 = logging.getLogger('d.e.f')
Vinay Sajipc31be632010-09-06 22:18:20 +00002003
2004 f = ContextFilter()
2005 a1.addFilter(f)
2006 a2.addFilter(f)
Vinay Sajip9a6b4002010-12-14 19:40:21 +00002007 a1.debug('A debug message')
2008 a1.info('An info message with %s', 'some parameters')
Vinay Sajipc31be632010-09-06 22:18:20 +00002009 for x in range(10):
2010 lvl = choice(levels)
2011 lvlname = logging.getLevelName(lvl)
Vinay Sajip9a6b4002010-12-14 19:40:21 +00002012 a2.log(lvl, 'A message at %s level with %d %s', lvlname, 2, 'parameters')
Vinay Sajipc31be632010-09-06 22:18:20 +00002013
2014which, when run, produces something like::
2015
2016 2010-09-06 22:38:15,292 a.b.c DEBUG IP: 123.231.231.123 User: fred A debug message
2017 2010-09-06 22:38:15,300 a.b.c INFO IP: 192.168.0.1 User: sheila An info message with some parameters
2018 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
2019 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
2020 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
2021 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
2022 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
2023 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
2024 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
2025 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
2026 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
2027 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
2028
2029
Vinay Sajipd31f3632010-06-29 15:31:15 +00002030.. _multiple-processes:
2031
Vinay Sajipa7471bf2009-08-15 23:23:37 +00002032Logging to a single file from multiple processes
2033------------------------------------------------
2034
2035Although logging is thread-safe, and logging to a single file from multiple
2036threads in a single process *is* supported, logging to a single file from
2037*multiple processes* is *not* supported, because there is no standard way to
2038serialize access to a single file across multiple processes in Python. If you
Vinay Sajip121a1c42010-09-08 10:46:15 +00002039need to log to a single file from multiple processes, one way of doing this is
2040to have all the processes log to a :class:`SocketHandler`, and have a separate
2041process which implements a socket server which reads from the socket and logs
2042to file. (If you prefer, you can dedicate one thread in one of the existing
2043processes to perform this function.) The following section documents this
2044approach in more detail and includes a working socket receiver which can be
2045used as a starting point for you to adapt in your own applications.
Vinay Sajipa7471bf2009-08-15 23:23:37 +00002046
Vinay Sajip5a92b132009-08-15 23:35:08 +00002047If you are using a recent version of Python which includes the
Vinay Sajip121a1c42010-09-08 10:46:15 +00002048:mod:`multiprocessing` module, you could write your own handler which uses the
Vinay Sajip5a92b132009-08-15 23:35:08 +00002049:class:`Lock` class from this module to serialize access to the file from
2050your processes. The existing :class:`FileHandler` and subclasses do not make
2051use of :mod:`multiprocessing` at present, though they may do so in the future.
Vinay Sajip8c6b0a52009-08-17 13:17:47 +00002052Note that at present, the :mod:`multiprocessing` module does not provide
2053working lock functionality on all platforms (see
2054http://bugs.python.org/issue3770).
Vinay Sajip5a92b132009-08-15 23:35:08 +00002055
Vinay Sajip121a1c42010-09-08 10:46:15 +00002056.. currentmodule:: logging.handlers
2057
2058Alternatively, you can use a ``Queue`` and a :class:`QueueHandler` to send
2059all logging events to one of the processes in your multi-process application.
2060The following example script demonstrates how you can do this; in the example
2061a separate listener process listens for events sent by other processes and logs
2062them according to its own logging configuration. Although the example only
2063demonstrates one way of doing it (for example, you may want to use a listener
2064thread rather than a separate listener process - the implementation would be
2065analogous) it does allow for completely different logging configurations for
2066the listener and the other processes in your application, and can be used as
2067the basis for code meeting your own specific requirements::
2068
2069 # You'll need these imports in your own code
2070 import logging
2071 import logging.handlers
2072 import multiprocessing
2073
2074 # Next two import lines for this demo only
2075 from random import choice, random
2076 import time
2077
2078 #
2079 # Because you'll want to define the logging configurations for listener and workers, the
2080 # listener and worker process functions take a configurer parameter which is a callable
2081 # for configuring logging for that process. These functions are also passed the queue,
2082 # which they use for communication.
2083 #
2084 # In practice, you can configure the listener however you want, but note that in this
2085 # simple example, the listener does not apply level or filter logic to received records.
2086 # In practice, you would probably want to do ths logic in the worker processes, to avoid
2087 # sending events which would be filtered out between processes.
2088 #
2089 # The size of the rotated files is made small so you can see the results easily.
2090 def listener_configurer():
2091 root = logging.getLogger()
2092 h = logging.handlers.RotatingFileHandler('/tmp/mptest.log', 'a', 300, 10)
2093 f = logging.Formatter('%(asctime)s %(processName)-10s %(name)s %(levelname)-8s %(message)s')
2094 h.setFormatter(f)
2095 root.addHandler(h)
2096
2097 # This is the listener process top-level loop: wait for logging events
2098 # (LogRecords)on the queue and handle them, quit when you get a None for a
2099 # LogRecord.
2100 def listener_process(queue, configurer):
2101 configurer()
2102 while True:
2103 try:
2104 record = queue.get()
2105 if record is None: # We send this as a sentinel to tell the listener to quit.
2106 break
2107 logger = logging.getLogger(record.name)
2108 logger.handle(record) # No level or filter logic applied - just do it!
2109 except (KeyboardInterrupt, SystemExit):
2110 raise
2111 except:
2112 import sys, traceback
2113 print >> sys.stderr, 'Whoops! Problem:'
2114 traceback.print_exc(file=sys.stderr)
2115
2116 # Arrays used for random selections in this demo
2117
2118 LEVELS = [logging.DEBUG, logging.INFO, logging.WARNING,
2119 logging.ERROR, logging.CRITICAL]
2120
2121 LOGGERS = ['a.b.c', 'd.e.f']
2122
2123 MESSAGES = [
2124 'Random message #1',
2125 'Random message #2',
2126 'Random message #3',
2127 ]
2128
2129 # The worker configuration is done at the start of the worker process run.
2130 # Note that on Windows you can't rely on fork semantics, so each process
2131 # will run the logging configuration code when it starts.
2132 def worker_configurer(queue):
2133 h = logging.handlers.QueueHandler(queue) # Just the one handler needed
2134 root = logging.getLogger()
2135 root.addHandler(h)
2136 root.setLevel(logging.DEBUG) # send all messages, for demo; no other level or filter logic applied.
2137
2138 # This is the worker process top-level loop, which just logs ten events with
2139 # random intervening delays before terminating.
2140 # The print messages are just so you know it's doing something!
2141 def worker_process(queue, configurer):
2142 configurer(queue)
2143 name = multiprocessing.current_process().name
2144 print('Worker started: %s' % name)
2145 for i in range(10):
2146 time.sleep(random())
2147 logger = logging.getLogger(choice(LOGGERS))
2148 level = choice(LEVELS)
2149 message = choice(MESSAGES)
2150 logger.log(level, message)
2151 print('Worker finished: %s' % name)
2152
2153 # Here's where the demo gets orchestrated. Create the queue, create and start
2154 # the listener, create ten workers and start them, wait for them to finish,
2155 # then send a None to the queue to tell the listener to finish.
2156 def main():
2157 queue = multiprocessing.Queue(-1)
2158 listener = multiprocessing.Process(target=listener_process,
2159 args=(queue, listener_configurer))
2160 listener.start()
2161 workers = []
2162 for i in range(10):
2163 worker = multiprocessing.Process(target=worker_process,
2164 args=(queue, worker_configurer))
2165 workers.append(worker)
2166 worker.start()
2167 for w in workers:
2168 w.join()
2169 queue.put_nowait(None)
2170 listener.join()
2171
2172 if __name__ == '__main__':
2173 main()
2174
2175
2176.. currentmodule:: logging
2177
Benjamin Peterson8719ad52009-09-11 22:24:02 +00002178
Georg Brandl116aa622007-08-15 14:28:22 +00002179.. _network-logging:
2180
2181Sending and receiving logging events across a network
2182-----------------------------------------------------
2183
2184Let's say you want to send logging events across a network, and handle them at
2185the receiving end. A simple way of doing this is attaching a
2186:class:`SocketHandler` instance to the root logger at the sending end::
2187
2188 import logging, logging.handlers
2189
2190 rootLogger = logging.getLogger('')
2191 rootLogger.setLevel(logging.DEBUG)
2192 socketHandler = logging.handlers.SocketHandler('localhost',
2193 logging.handlers.DEFAULT_TCP_LOGGING_PORT)
2194 # don't bother with a formatter, since a socket handler sends the event as
2195 # an unformatted pickle
2196 rootLogger.addHandler(socketHandler)
2197
2198 # Now, we can log to the root logger, or any other logger. First the root...
2199 logging.info('Jackdaws love my big sphinx of quartz.')
2200
2201 # Now, define a couple of other loggers which might represent areas in your
2202 # application:
2203
2204 logger1 = logging.getLogger('myapp.area1')
2205 logger2 = logging.getLogger('myapp.area2')
2206
2207 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
2208 logger1.info('How quickly daft jumping zebras vex.')
2209 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
2210 logger2.error('The five boxing wizards jump quickly.')
2211
Alexandre Vassalottice261952008-05-12 02:31:37 +00002212At the receiving end, you can set up a receiver using the :mod:`socketserver`
Georg Brandl116aa622007-08-15 14:28:22 +00002213module. Here is a basic working example::
2214
Georg Brandla35f4b92009-05-31 16:41:59 +00002215 import pickle
Georg Brandl116aa622007-08-15 14:28:22 +00002216 import logging
2217 import logging.handlers
Alexandre Vassalottice261952008-05-12 02:31:37 +00002218 import socketserver
Georg Brandl116aa622007-08-15 14:28:22 +00002219 import struct
2220
2221
Alexandre Vassalottice261952008-05-12 02:31:37 +00002222 class LogRecordStreamHandler(socketserver.StreamRequestHandler):
Georg Brandl116aa622007-08-15 14:28:22 +00002223 """Handler for a streaming logging request.
2224
2225 This basically logs the record using whatever logging policy is
2226 configured locally.
2227 """
2228
2229 def handle(self):
2230 """
2231 Handle multiple requests - each expected to be a 4-byte length,
2232 followed by the LogRecord in pickle format. Logs the record
2233 according to whatever policy is configured locally.
2234 """
Collin Winter46334482007-09-10 00:49:57 +00002235 while True:
Georg Brandl116aa622007-08-15 14:28:22 +00002236 chunk = self.connection.recv(4)
2237 if len(chunk) < 4:
2238 break
Vinay Sajip9a6b4002010-12-14 19:40:21 +00002239 slen = struct.unpack('>L', chunk)[0]
Georg Brandl116aa622007-08-15 14:28:22 +00002240 chunk = self.connection.recv(slen)
2241 while len(chunk) < slen:
2242 chunk = chunk + self.connection.recv(slen - len(chunk))
2243 obj = self.unPickle(chunk)
2244 record = logging.makeLogRecord(obj)
2245 self.handleLogRecord(record)
2246
2247 def unPickle(self, data):
Georg Brandla35f4b92009-05-31 16:41:59 +00002248 return pickle.loads(data)
Georg Brandl116aa622007-08-15 14:28:22 +00002249
2250 def handleLogRecord(self, record):
2251 # if a name is specified, we use the named logger rather than the one
2252 # implied by the record.
2253 if self.server.logname is not None:
2254 name = self.server.logname
2255 else:
2256 name = record.name
2257 logger = logging.getLogger(name)
2258 # N.B. EVERY record gets logged. This is because Logger.handle
2259 # is normally called AFTER logger-level filtering. If you want
2260 # to do filtering, do it at the client end to save wasting
2261 # cycles and network bandwidth!
2262 logger.handle(record)
2263
Alexandre Vassalottice261952008-05-12 02:31:37 +00002264 class LogRecordSocketReceiver(socketserver.ThreadingTCPServer):
Vinay Sajip9a6b4002010-12-14 19:40:21 +00002265 """
2266 Simple TCP socket-based logging receiver suitable for testing.
Georg Brandl116aa622007-08-15 14:28:22 +00002267 """
2268
2269 allow_reuse_address = 1
2270
2271 def __init__(self, host='localhost',
2272 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
2273 handler=LogRecordStreamHandler):
Alexandre Vassalottice261952008-05-12 02:31:37 +00002274 socketserver.ThreadingTCPServer.__init__(self, (host, port), handler)
Georg Brandl116aa622007-08-15 14:28:22 +00002275 self.abort = 0
2276 self.timeout = 1
2277 self.logname = None
2278
2279 def serve_until_stopped(self):
2280 import select
2281 abort = 0
2282 while not abort:
2283 rd, wr, ex = select.select([self.socket.fileno()],
2284 [], [],
2285 self.timeout)
2286 if rd:
2287 self.handle_request()
2288 abort = self.abort
2289
2290 def main():
2291 logging.basicConfig(
Vinay Sajip9a6b4002010-12-14 19:40:21 +00002292 format='%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s')
Georg Brandl116aa622007-08-15 14:28:22 +00002293 tcpserver = LogRecordSocketReceiver()
Vinay Sajip9a6b4002010-12-14 19:40:21 +00002294 print('About to start TCP server...')
Georg Brandl116aa622007-08-15 14:28:22 +00002295 tcpserver.serve_until_stopped()
2296
Vinay Sajip9a6b4002010-12-14 19:40:21 +00002297 if __name__ == '__main__':
Georg Brandl116aa622007-08-15 14:28:22 +00002298 main()
2299
2300First run the server, and then the client. On the client side, nothing is
2301printed on the console; on the server side, you should see something like::
2302
2303 About to start TCP server...
2304 59 root INFO Jackdaws love my big sphinx of quartz.
2305 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
2306 69 myapp.area1 INFO How quickly daft jumping zebras vex.
2307 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
2308 69 myapp.area2 ERROR The five boxing wizards jump quickly.
2309
Vinay Sajipc15dfd62010-07-06 15:08:55 +00002310Note that there are some security issues with pickle in some scenarios. If
2311these affect you, you can use an alternative serialization scheme by overriding
2312the :meth:`makePickle` method and implementing your alternative there, as
2313well as adapting the above script to use your alternative serialization.
2314
Vinay Sajip4039aff2010-09-11 10:25:28 +00002315.. _arbitrary-object-messages:
2316
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002317Using arbitrary objects as messages
2318-----------------------------------
2319
2320In the preceding sections and examples, it has been assumed that the message
2321passed when logging the event is a string. However, this is not the only
2322possibility. You can pass an arbitrary object as a message, and its
2323:meth:`__str__` method will be called when the logging system needs to convert
2324it to a string representation. In fact, if you want to, you can avoid
2325computing a string representation altogether - for example, the
2326:class:`SocketHandler` emits an event by pickling it and sending it over the
2327wire.
2328
Vinay Sajip55778922010-09-23 09:09:15 +00002329Dealing with handlers that block
2330--------------------------------
2331
2332.. currentmodule:: logging.handlers
2333
2334Sometimes you have to get your logging handlers to do their work without
2335blocking the thread you’re logging from. This is common in Web applications,
2336though of course it also occurs in other scenarios.
2337
2338A common culprit which demonstrates sluggish behaviour is the
2339:class:`SMTPHandler`: sending emails can take a long time, for a
2340number of reasons outside the developer’s control (for example, a poorly
2341performing mail or network infrastructure). But almost any network-based
2342handler can block: Even a :class:`SocketHandler` operation may do a
2343DNS query under the hood which is too slow (and this query can be deep in the
2344socket library code, below the Python layer, and outside your control).
2345
2346One solution is to use a two-part approach. For the first part, attach only a
2347:class:`QueueHandler` to those loggers which are accessed from
2348performance-critical threads. They simply write to their queue, which can be
2349sized to a large enough capacity or initialized with no upper bound to their
2350size. The write to the queue will typically be accepted quickly, though you
2351will probably need to catch the :ref:`queue.Full` exception as a precaution
2352in your code. If you are a library developer who has performance-critical
2353threads in their code, be sure to document this (together with a suggestion to
2354attach only ``QueueHandlers`` to your loggers) for the benefit of other
2355developers who will use your code.
2356
2357The second part of the solution is :class:`QueueListener`, which has been
2358designed as the counterpart to :class:`QueueHandler`. A
2359:class:`QueueListener` is very simple: it’s passed a queue and some handlers,
2360and it fires up an internal thread which listens to its queue for LogRecords
2361sent from ``QueueHandlers`` (or any other source of ``LogRecords``, for that
2362matter). The ``LogRecords`` are removed from the queue and passed to the
2363handlers for processing.
2364
2365The advantage of having a separate :class:`QueueListener` class is that you
2366can use the same instance to service multiple ``QueueHandlers``. This is more
2367resource-friendly than, say, having threaded versions of the existing handler
2368classes, which would eat up one thread per handler for no particular benefit.
2369
2370An example of using these two classes follows (imports omitted)::
2371
2372 que = queue.Queue(-1) # no limit on size
2373 queue_handler = QueueHandler(que)
2374 handler = logging.StreamHandler()
2375 listener = QueueListener(que, handler)
2376 root = logging.getLogger()
2377 root.addHandler(queue_handler)
2378 formatter = logging.Formatter('%(threadName)s: %(message)s')
2379 handler.setFormatter(formatter)
2380 listener.start()
2381 # The log output will display the thread which generated
2382 # the event (the main thread) rather than the internal
2383 # thread which monitors the internal queue. This is what
2384 # you want to happen.
2385 root.warning('Look out!')
2386 listener.stop()
2387
2388which, when run, will produce::
2389
2390 MainThread: Look out!
2391
2392
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002393Optimization
2394------------
2395
2396Formatting of message arguments is deferred until it cannot be avoided.
2397However, computing the arguments passed to the logging method can also be
2398expensive, and you may want to avoid doing it if the logger will just throw
2399away your event. To decide what to do, you can call the :meth:`isEnabledFor`
2400method which takes a level argument and returns true if the event would be
2401created by the Logger for that level of call. You can write code like this::
2402
2403 if logger.isEnabledFor(logging.DEBUG):
Vinay Sajip9a6b4002010-12-14 19:40:21 +00002404 logger.debug('Message with %s, %s', expensive_func1(),
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002405 expensive_func2())
2406
2407so that if the logger's threshold is set above ``DEBUG``, the calls to
2408:func:`expensive_func1` and :func:`expensive_func2` are never made.
2409
2410There are other optimizations which can be made for specific applications which
2411need more precise control over what logging information is collected. Here's a
2412list of things you can do to avoid processing during logging which you don't
2413need:
2414
2415+-----------------------------------------------+----------------------------------------+
2416| What you don't want to collect | How to avoid collecting it |
2417+===============================================+========================================+
2418| Information about where calls were made from. | Set ``logging._srcfile`` to ``None``. |
2419+-----------------------------------------------+----------------------------------------+
2420| Threading information. | Set ``logging.logThreads`` to ``0``. |
2421+-----------------------------------------------+----------------------------------------+
2422| Process information. | Set ``logging.logProcesses`` to ``0``. |
2423+-----------------------------------------------+----------------------------------------+
2424
2425Also note that the core logging module only includes the basic handlers. If
2426you don't import :mod:`logging.handlers` and :mod:`logging.config`, they won't
2427take up any memory.
2428
2429.. _handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002430
2431Handler Objects
2432---------------
2433
2434Handlers have the following attributes and methods. Note that :class:`Handler`
2435is never instantiated directly; this class acts as a base for more useful
2436subclasses. However, the :meth:`__init__` method in subclasses needs to call
2437:meth:`Handler.__init__`.
2438
2439
2440.. method:: Handler.__init__(level=NOTSET)
2441
2442 Initializes the :class:`Handler` instance by setting its level, setting the list
2443 of filters to the empty list and creating a lock (using :meth:`createLock`) for
2444 serializing access to an I/O mechanism.
2445
2446
2447.. method:: Handler.createLock()
2448
2449 Initializes a thread lock which can be used to serialize access to underlying
2450 I/O functionality which may not be threadsafe.
2451
2452
2453.. method:: Handler.acquire()
2454
2455 Acquires the thread lock created with :meth:`createLock`.
2456
2457
2458.. method:: Handler.release()
2459
2460 Releases the thread lock acquired with :meth:`acquire`.
2461
2462
2463.. method:: Handler.setLevel(lvl)
2464
2465 Sets the threshold for this handler to *lvl*. Logging messages which are less
2466 severe than *lvl* will be ignored. When a handler is created, the level is set
2467 to :const:`NOTSET` (which causes all messages to be processed).
2468
2469
2470.. method:: Handler.setFormatter(form)
2471
2472 Sets the :class:`Formatter` for this handler to *form*.
2473
2474
2475.. method:: Handler.addFilter(filt)
2476
2477 Adds the specified filter *filt* to this handler.
2478
2479
2480.. method:: Handler.removeFilter(filt)
2481
2482 Removes the specified filter *filt* from this handler.
2483
2484
2485.. method:: Handler.filter(record)
2486
2487 Applies this handler's filters to the record and returns a true value if the
2488 record is to be processed.
2489
2490
2491.. method:: Handler.flush()
2492
2493 Ensure all logging output has been flushed. This version does nothing and is
2494 intended to be implemented by subclasses.
2495
2496
2497.. method:: Handler.close()
2498
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002499 Tidy up any resources used by the handler. This version does no output but
2500 removes the handler from an internal list of handlers which is closed when
2501 :func:`shutdown` is called. Subclasses should ensure that this gets called
2502 from overridden :meth:`close` methods.
Georg Brandl116aa622007-08-15 14:28:22 +00002503
2504
2505.. method:: Handler.handle(record)
2506
2507 Conditionally emits the specified logging record, depending on filters which may
2508 have been added to the handler. Wraps the actual emission of the record with
2509 acquisition/release of the I/O thread lock.
2510
2511
2512.. method:: Handler.handleError(record)
2513
2514 This method should be called from handlers when an exception is encountered
2515 during an :meth:`emit` call. By default it does nothing, which means that
2516 exceptions get silently ignored. This is what is mostly wanted for a logging
2517 system - most users will not care about errors in the logging system, they are
2518 more interested in application errors. You could, however, replace this with a
2519 custom handler if you wish. The specified record is the one which was being
2520 processed when the exception occurred.
2521
2522
2523.. method:: Handler.format(record)
2524
2525 Do formatting for a record - if a formatter is set, use it. Otherwise, use the
2526 default formatter for the module.
2527
2528
2529.. method:: Handler.emit(record)
2530
2531 Do whatever it takes to actually log the specified logging record. This version
2532 is intended to be implemented by subclasses and so raises a
2533 :exc:`NotImplementedError`.
2534
2535
Vinay Sajipd31f3632010-06-29 15:31:15 +00002536.. _stream-handler:
2537
Georg Brandl116aa622007-08-15 14:28:22 +00002538StreamHandler
2539^^^^^^^^^^^^^
2540
2541The :class:`StreamHandler` class, located in the core :mod:`logging` package,
2542sends logging output to streams such as *sys.stdout*, *sys.stderr* or any
2543file-like object (or, more precisely, any object which supports :meth:`write`
2544and :meth:`flush` methods).
2545
2546
Benjamin Peterson1baf4652009-12-31 03:11:23 +00002547.. currentmodule:: logging
2548
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002549.. class:: StreamHandler(stream=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002550
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002551 Returns a new instance of the :class:`StreamHandler` class. If *stream* is
Georg Brandl116aa622007-08-15 14:28:22 +00002552 specified, the instance will use it for logging output; otherwise, *sys.stderr*
2553 will be used.
2554
2555
Benjamin Petersone41251e2008-04-25 01:59:09 +00002556 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002557
Benjamin Petersone41251e2008-04-25 01:59:09 +00002558 If a formatter is specified, it is used to format the record. The record
2559 is then written to the stream with a trailing newline. If exception
2560 information is present, it is formatted using
2561 :func:`traceback.print_exception` and appended to the stream.
Georg Brandl116aa622007-08-15 14:28:22 +00002562
2563
Benjamin Petersone41251e2008-04-25 01:59:09 +00002564 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00002565
Benjamin Petersone41251e2008-04-25 01:59:09 +00002566 Flushes the stream by calling its :meth:`flush` method. Note that the
2567 :meth:`close` method is inherited from :class:`Handler` and so does
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002568 no output, so an explicit :meth:`flush` call may be needed at times.
Georg Brandl116aa622007-08-15 14:28:22 +00002569
Vinay Sajip05ed6952010-10-20 20:34:09 +00002570.. versionchanged:: 3.2
2571 The ``StreamHandler`` class now has a ``terminator`` attribute, default
Vinay Sajip9a6b4002010-12-14 19:40:21 +00002572 value ``'\n'``, which is used as the terminator when writing a formatted
Vinay Sajip05ed6952010-10-20 20:34:09 +00002573 record to a stream. If you don't want this newline termination, you can
2574 set the handler instance's ``terminator`` attribute to the empty string.
Georg Brandl116aa622007-08-15 14:28:22 +00002575
Vinay Sajipd31f3632010-06-29 15:31:15 +00002576.. _file-handler:
2577
Georg Brandl116aa622007-08-15 14:28:22 +00002578FileHandler
2579^^^^^^^^^^^
2580
2581The :class:`FileHandler` class, located in the core :mod:`logging` package,
2582sends logging output to a disk file. It inherits the output functionality from
2583:class:`StreamHandler`.
2584
2585
Vinay Sajipd31f3632010-06-29 15:31:15 +00002586.. class:: FileHandler(filename, mode='a', encoding=None, delay=False)
Georg Brandl116aa622007-08-15 14:28:22 +00002587
2588 Returns a new instance of the :class:`FileHandler` class. The specified file is
2589 opened and used as the stream for logging. If *mode* is not specified,
2590 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Christian Heimese7a15bb2008-01-24 16:21:45 +00002591 with that encoding. If *delay* is true, then file opening is deferred until the
2592 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002593
2594
Benjamin Petersone41251e2008-04-25 01:59:09 +00002595 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002596
Benjamin Petersone41251e2008-04-25 01:59:09 +00002597 Closes the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002598
2599
Benjamin Petersone41251e2008-04-25 01:59:09 +00002600 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002601
Benjamin Petersone41251e2008-04-25 01:59:09 +00002602 Outputs the record to the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002603
Georg Brandl1eb40bc2010-12-03 15:30:09 +00002604
Vinay Sajipd31f3632010-06-29 15:31:15 +00002605.. _null-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002606
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002607NullHandler
2608^^^^^^^^^^^
2609
2610.. versionadded:: 3.1
2611
2612The :class:`NullHandler` class, located in the core :mod:`logging` package,
Vinay Sajip9a6b4002010-12-14 19:40:21 +00002613does not do any formatting or output. It is essentially a 'no-op' handler
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002614for use by library developers.
2615
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002616.. class:: NullHandler()
2617
2618 Returns a new instance of the :class:`NullHandler` class.
2619
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002620 .. method:: emit(record)
2621
2622 This method does nothing.
2623
Vinay Sajip76ca3b42010-09-27 13:53:47 +00002624 .. method:: handle(record)
2625
2626 This method does nothing.
2627
2628 .. method:: createLock()
2629
Senthil Kumaran46a48be2010-10-15 13:10:10 +00002630 This method returns ``None`` for the lock, since there is no
Vinay Sajip76ca3b42010-09-27 13:53:47 +00002631 underlying I/O to which access needs to be serialized.
2632
2633
Vinay Sajip26a2d5e2009-01-10 13:37:26 +00002634See :ref:`library-config` for more information on how to use
2635:class:`NullHandler`.
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00002636
Vinay Sajipd31f3632010-06-29 15:31:15 +00002637.. _watched-file-handler:
2638
Georg Brandl116aa622007-08-15 14:28:22 +00002639WatchedFileHandler
2640^^^^^^^^^^^^^^^^^^
2641
Benjamin Peterson058e31e2009-01-16 03:54:08 +00002642.. currentmodule:: logging.handlers
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002643
Georg Brandl116aa622007-08-15 14:28:22 +00002644The :class:`WatchedFileHandler` class, located in the :mod:`logging.handlers`
2645module, is a :class:`FileHandler` which watches the file it is logging to. If
2646the file changes, it is closed and reopened using the file name.
2647
2648A file change can happen because of usage of programs such as *newsyslog* and
2649*logrotate* which perform log file rotation. This handler, intended for use
2650under Unix/Linux, watches the file to see if it has changed since the last emit.
2651(A file is deemed to have changed if its device or inode have changed.) If the
2652file has changed, the old file stream is closed, and the file opened to get a
2653new stream.
2654
2655This handler is not appropriate for use under Windows, because under Windows
2656open log files cannot be moved or renamed - logging opens the files with
2657exclusive locks - and so there is no need for such a handler. Furthermore,
2658*ST_INO* is not supported under Windows; :func:`stat` always returns zero for
2659this value.
2660
2661
Christian Heimese7a15bb2008-01-24 16:21:45 +00002662.. class:: WatchedFileHandler(filename[,mode[, encoding[, delay]]])
Georg Brandl116aa622007-08-15 14:28:22 +00002663
2664 Returns a new instance of the :class:`WatchedFileHandler` class. The specified
2665 file is opened and used as the stream for logging. If *mode* is not specified,
2666 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Christian Heimese7a15bb2008-01-24 16:21:45 +00002667 with that encoding. If *delay* is true, then file opening is deferred until the
2668 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002669
2670
Benjamin Petersone41251e2008-04-25 01:59:09 +00002671 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002672
Benjamin Petersone41251e2008-04-25 01:59:09 +00002673 Outputs the record to the file, but first checks to see if the file has
2674 changed. If it has, the existing stream is flushed and closed and the
2675 file opened again, before outputting the record to the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002676
Vinay Sajipd31f3632010-06-29 15:31:15 +00002677.. _rotating-file-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002678
2679RotatingFileHandler
2680^^^^^^^^^^^^^^^^^^^
2681
2682The :class:`RotatingFileHandler` class, located in the :mod:`logging.handlers`
2683module, supports rotation of disk log files.
2684
2685
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002686.. class:: RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0)
Georg Brandl116aa622007-08-15 14:28:22 +00002687
2688 Returns a new instance of the :class:`RotatingFileHandler` class. The specified
2689 file is opened and used as the stream for logging. If *mode* is not specified,
Christian Heimese7a15bb2008-01-24 16:21:45 +00002690 ``'a'`` is used. If *encoding* is not *None*, it is used to open the file
2691 with that encoding. If *delay* is true, then file opening is deferred until the
2692 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002693
2694 You can use the *maxBytes* and *backupCount* values to allow the file to
2695 :dfn:`rollover` at a predetermined size. When the size is about to be exceeded,
2696 the file is closed and a new file is silently opened for output. Rollover occurs
2697 whenever the current log file is nearly *maxBytes* in length; if *maxBytes* is
2698 zero, rollover never occurs. If *backupCount* is non-zero, the system will save
Vinay Sajip9a6b4002010-12-14 19:40:21 +00002699 old log files by appending the extensions '.1', '.2' etc., to the filename. For
Georg Brandl116aa622007-08-15 14:28:22 +00002700 example, with a *backupCount* of 5 and a base file name of :file:`app.log`, you
2701 would get :file:`app.log`, :file:`app.log.1`, :file:`app.log.2`, up to
2702 :file:`app.log.5`. The file being written to is always :file:`app.log`. When
2703 this file is filled, it is closed and renamed to :file:`app.log.1`, and if files
2704 :file:`app.log.1`, :file:`app.log.2`, etc. exist, then they are renamed to
2705 :file:`app.log.2`, :file:`app.log.3` etc. respectively.
2706
2707
Benjamin Petersone41251e2008-04-25 01:59:09 +00002708 .. method:: doRollover()
Georg Brandl116aa622007-08-15 14:28:22 +00002709
Benjamin Petersone41251e2008-04-25 01:59:09 +00002710 Does a rollover, as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002711
2712
Benjamin Petersone41251e2008-04-25 01:59:09 +00002713 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002714
Benjamin Petersone41251e2008-04-25 01:59:09 +00002715 Outputs the record to the file, catering for rollover as described
2716 previously.
Georg Brandl116aa622007-08-15 14:28:22 +00002717
Vinay Sajipd31f3632010-06-29 15:31:15 +00002718.. _timed-rotating-file-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002719
2720TimedRotatingFileHandler
2721^^^^^^^^^^^^^^^^^^^^^^^^
2722
2723The :class:`TimedRotatingFileHandler` class, located in the
2724:mod:`logging.handlers` module, supports rotation of disk log files at certain
2725timed intervals.
2726
2727
Vinay Sajipd31f3632010-06-29 15:31:15 +00002728.. class:: TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False)
Georg Brandl116aa622007-08-15 14:28:22 +00002729
2730 Returns a new instance of the :class:`TimedRotatingFileHandler` class. The
2731 specified file is opened and used as the stream for logging. On rotating it also
2732 sets the filename suffix. Rotating happens based on the product of *when* and
2733 *interval*.
2734
2735 You can use the *when* to specify the type of *interval*. The list of possible
Georg Brandl0c77a822008-06-10 16:37:50 +00002736 values is below. Note that they are not case sensitive.
Georg Brandl116aa622007-08-15 14:28:22 +00002737
Christian Heimesb558a2e2008-03-02 22:46:37 +00002738 +----------------+-----------------------+
2739 | Value | Type of interval |
2740 +================+=======================+
2741 | ``'S'`` | Seconds |
2742 +----------------+-----------------------+
2743 | ``'M'`` | Minutes |
2744 +----------------+-----------------------+
2745 | ``'H'`` | Hours |
2746 +----------------+-----------------------+
2747 | ``'D'`` | Days |
2748 +----------------+-----------------------+
2749 | ``'W'`` | Week day (0=Monday) |
2750 +----------------+-----------------------+
2751 | ``'midnight'`` | Roll over at midnight |
2752 +----------------+-----------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00002753
Christian Heimesb558a2e2008-03-02 22:46:37 +00002754 The system will save old log files by appending extensions to the filename.
2755 The extensions are date-and-time based, using the strftime format
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00002756 ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on the
Georg Brandl3dbca812008-07-23 16:10:53 +00002757 rollover interval.
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00002758
2759 When computing the next rollover time for the first time (when the handler
2760 is created), the last modification time of an existing log file, or else
2761 the current time, is used to compute when the next rotation will occur.
2762
Georg Brandl0c77a822008-06-10 16:37:50 +00002763 If the *utc* argument is true, times in UTC will be used; otherwise
2764 local time is used.
2765
2766 If *backupCount* is nonzero, at most *backupCount* files
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00002767 will be kept, and if more would be created when rollover occurs, the oldest
2768 one is deleted. The deletion logic uses the interval to determine which
2769 files to delete, so changing the interval may leave old files lying around.
Georg Brandl116aa622007-08-15 14:28:22 +00002770
Vinay Sajipd31f3632010-06-29 15:31:15 +00002771 If *delay* is true, then file opening is deferred until the first call to
2772 :meth:`emit`.
2773
Georg Brandl116aa622007-08-15 14:28:22 +00002774
Benjamin Petersone41251e2008-04-25 01:59:09 +00002775 .. method:: doRollover()
Georg Brandl116aa622007-08-15 14:28:22 +00002776
Benjamin Petersone41251e2008-04-25 01:59:09 +00002777 Does a rollover, as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002778
2779
Benjamin Petersone41251e2008-04-25 01:59:09 +00002780 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002781
Benjamin Petersone41251e2008-04-25 01:59:09 +00002782 Outputs the record to the file, catering for rollover as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002783
2784
Vinay Sajipd31f3632010-06-29 15:31:15 +00002785.. _socket-handler:
2786
Georg Brandl116aa622007-08-15 14:28:22 +00002787SocketHandler
2788^^^^^^^^^^^^^
2789
2790The :class:`SocketHandler` class, located in the :mod:`logging.handlers` module,
2791sends logging output to a network socket. The base class uses a TCP socket.
2792
2793
2794.. class:: SocketHandler(host, port)
2795
2796 Returns a new instance of the :class:`SocketHandler` class intended to
2797 communicate with a remote machine whose address is given by *host* and *port*.
2798
2799
Benjamin Petersone41251e2008-04-25 01:59:09 +00002800 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002801
Benjamin Petersone41251e2008-04-25 01:59:09 +00002802 Closes the socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002803
2804
Benjamin Petersone41251e2008-04-25 01:59:09 +00002805 .. method:: emit()
Georg Brandl116aa622007-08-15 14:28:22 +00002806
Benjamin Petersone41251e2008-04-25 01:59:09 +00002807 Pickles the record's attribute dictionary and writes it to the socket in
2808 binary format. If there is an error with the socket, silently drops the
2809 packet. If the connection was previously lost, re-establishes the
2810 connection. To unpickle the record at the receiving end into a
2811 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl116aa622007-08-15 14:28:22 +00002812
2813
Benjamin Petersone41251e2008-04-25 01:59:09 +00002814 .. method:: handleError()
Georg Brandl116aa622007-08-15 14:28:22 +00002815
Benjamin Petersone41251e2008-04-25 01:59:09 +00002816 Handles an error which has occurred during :meth:`emit`. The most likely
2817 cause is a lost connection. Closes the socket so that we can retry on the
2818 next event.
Georg Brandl116aa622007-08-15 14:28:22 +00002819
2820
Benjamin Petersone41251e2008-04-25 01:59:09 +00002821 .. method:: makeSocket()
Georg Brandl116aa622007-08-15 14:28:22 +00002822
Benjamin Petersone41251e2008-04-25 01:59:09 +00002823 This is a factory method which allows subclasses to define the precise
2824 type of socket they want. The default implementation creates a TCP socket
2825 (:const:`socket.SOCK_STREAM`).
Georg Brandl116aa622007-08-15 14:28:22 +00002826
2827
Benjamin Petersone41251e2008-04-25 01:59:09 +00002828 .. method:: makePickle(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002829
Benjamin Petersone41251e2008-04-25 01:59:09 +00002830 Pickles the record's attribute dictionary in binary format with a length
2831 prefix, and returns it ready for transmission across the socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002832
Vinay Sajipd31f3632010-06-29 15:31:15 +00002833 Note that pickles aren't completely secure. If you are concerned about
2834 security, you may want to override this method to implement a more secure
2835 mechanism. For example, you can sign pickles using HMAC and then verify
2836 them on the receiving end, or alternatively you can disable unpickling of
2837 global objects on the receiving end.
Georg Brandl116aa622007-08-15 14:28:22 +00002838
Benjamin Petersone41251e2008-04-25 01:59:09 +00002839 .. method:: send(packet)
Georg Brandl116aa622007-08-15 14:28:22 +00002840
Benjamin Petersone41251e2008-04-25 01:59:09 +00002841 Send a pickled string *packet* to the socket. This function allows for
2842 partial sends which can happen when the network is busy.
Georg Brandl116aa622007-08-15 14:28:22 +00002843
2844
Vinay Sajipd31f3632010-06-29 15:31:15 +00002845.. _datagram-handler:
2846
Georg Brandl116aa622007-08-15 14:28:22 +00002847DatagramHandler
2848^^^^^^^^^^^^^^^
2849
2850The :class:`DatagramHandler` class, located in the :mod:`logging.handlers`
2851module, inherits from :class:`SocketHandler` to support sending logging messages
2852over UDP sockets.
2853
2854
2855.. class:: DatagramHandler(host, port)
2856
2857 Returns a new instance of the :class:`DatagramHandler` class intended to
2858 communicate with a remote machine whose address is given by *host* and *port*.
2859
2860
Benjamin Petersone41251e2008-04-25 01:59:09 +00002861 .. method:: emit()
Georg Brandl116aa622007-08-15 14:28:22 +00002862
Benjamin Petersone41251e2008-04-25 01:59:09 +00002863 Pickles the record's attribute dictionary and writes it to the socket in
2864 binary format. If there is an error with the socket, silently drops the
2865 packet. To unpickle the record at the receiving end into a
2866 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl116aa622007-08-15 14:28:22 +00002867
2868
Benjamin Petersone41251e2008-04-25 01:59:09 +00002869 .. method:: makeSocket()
Georg Brandl116aa622007-08-15 14:28:22 +00002870
Benjamin Petersone41251e2008-04-25 01:59:09 +00002871 The factory method of :class:`SocketHandler` is here overridden to create
2872 a UDP socket (:const:`socket.SOCK_DGRAM`).
Georg Brandl116aa622007-08-15 14:28:22 +00002873
2874
Benjamin Petersone41251e2008-04-25 01:59:09 +00002875 .. method:: send(s)
Georg Brandl116aa622007-08-15 14:28:22 +00002876
Benjamin Petersone41251e2008-04-25 01:59:09 +00002877 Send a pickled string to a socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002878
2879
Vinay Sajipd31f3632010-06-29 15:31:15 +00002880.. _syslog-handler:
2881
Georg Brandl116aa622007-08-15 14:28:22 +00002882SysLogHandler
2883^^^^^^^^^^^^^
2884
2885The :class:`SysLogHandler` class, located in the :mod:`logging.handlers` module,
2886supports sending logging messages to a remote or local Unix syslog.
2887
2888
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002889.. class:: SysLogHandler(address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER, socktype=socket.SOCK_DGRAM)
Georg Brandl116aa622007-08-15 14:28:22 +00002890
2891 Returns a new instance of the :class:`SysLogHandler` class intended to
2892 communicate with a remote Unix machine whose address is given by *address* in
2893 the form of a ``(host, port)`` tuple. If *address* is not specified,
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002894 ``('localhost', 514)`` is used. The address is used to open a socket. An
Georg Brandl116aa622007-08-15 14:28:22 +00002895 alternative to providing a ``(host, port)`` tuple is providing an address as a
Vinay Sajip9a6b4002010-12-14 19:40:21 +00002896 string, for example '/dev/log'. In this case, a Unix domain socket is used to
Georg Brandl116aa622007-08-15 14:28:22 +00002897 send the message to the syslog. If *facility* is not specified,
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002898 :const:`LOG_USER` is used. The type of socket opened depends on the
2899 *socktype* argument, which defaults to :const:`socket.SOCK_DGRAM` and thus
2900 opens a UDP socket. To open a TCP socket (for use with the newer syslog
2901 daemons such as rsyslog), specify a value of :const:`socket.SOCK_STREAM`.
2902
Vinay Sajip972412d2010-09-23 20:31:24 +00002903 Note that if your server is not listening on UDP port 514,
2904 :class:`SysLogHandler` may appear not to work. In that case, check what
2905 address you should be using for a domain socket - it's system dependent.
Vinay Sajip9a6b4002010-12-14 19:40:21 +00002906 For example, on Linux it's usually '/dev/log' but on OS/X it's
2907 '/var/run/syslog'. You'll need to check your platform and use the
Vinay Sajip972412d2010-09-23 20:31:24 +00002908 appropriate address (you may need to do this check at runtime if your
2909 application needs to run on several platforms). On Windows, you pretty
2910 much have to use the UDP option.
2911
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002912 .. versionchanged:: 3.2
2913 *socktype* was added.
Georg Brandl116aa622007-08-15 14:28:22 +00002914
2915
Benjamin Petersone41251e2008-04-25 01:59:09 +00002916 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002917
Benjamin Petersone41251e2008-04-25 01:59:09 +00002918 Closes the socket to the remote host.
Georg Brandl116aa622007-08-15 14:28:22 +00002919
2920
Benjamin Petersone41251e2008-04-25 01:59:09 +00002921 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002922
Benjamin Petersone41251e2008-04-25 01:59:09 +00002923 The record is formatted, and then sent to the syslog server. If exception
2924 information is present, it is *not* sent to the server.
Georg Brandl116aa622007-08-15 14:28:22 +00002925
2926
Benjamin Petersone41251e2008-04-25 01:59:09 +00002927 .. method:: encodePriority(facility, priority)
Georg Brandl116aa622007-08-15 14:28:22 +00002928
Benjamin Petersone41251e2008-04-25 01:59:09 +00002929 Encodes the facility and priority into an integer. You can pass in strings
2930 or integers - if strings are passed, internal mapping dictionaries are
2931 used to convert them to integers.
Georg Brandl116aa622007-08-15 14:28:22 +00002932
Benjamin Peterson22005fc2010-04-11 16:25:06 +00002933 The symbolic ``LOG_`` values are defined in :class:`SysLogHandler` and
2934 mirror the values defined in the ``sys/syslog.h`` header file.
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002935
Georg Brandl88d7dbd2010-04-18 09:50:07 +00002936 **Priorities**
2937
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002938 +--------------------------+---------------+
2939 | Name (string) | Symbolic value|
2940 +==========================+===============+
2941 | ``alert`` | LOG_ALERT |
2942 +--------------------------+---------------+
2943 | ``crit`` or ``critical`` | LOG_CRIT |
2944 +--------------------------+---------------+
2945 | ``debug`` | LOG_DEBUG |
2946 +--------------------------+---------------+
2947 | ``emerg`` or ``panic`` | LOG_EMERG |
2948 +--------------------------+---------------+
2949 | ``err`` or ``error`` | LOG_ERR |
2950 +--------------------------+---------------+
2951 | ``info`` | LOG_INFO |
2952 +--------------------------+---------------+
2953 | ``notice`` | LOG_NOTICE |
2954 +--------------------------+---------------+
2955 | ``warn`` or ``warning`` | LOG_WARNING |
2956 +--------------------------+---------------+
2957
Georg Brandl88d7dbd2010-04-18 09:50:07 +00002958 **Facilities**
2959
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002960 +---------------+---------------+
2961 | Name (string) | Symbolic value|
2962 +===============+===============+
2963 | ``auth`` | LOG_AUTH |
2964 +---------------+---------------+
2965 | ``authpriv`` | LOG_AUTHPRIV |
2966 +---------------+---------------+
2967 | ``cron`` | LOG_CRON |
2968 +---------------+---------------+
2969 | ``daemon`` | LOG_DAEMON |
2970 +---------------+---------------+
2971 | ``ftp`` | LOG_FTP |
2972 +---------------+---------------+
2973 | ``kern`` | LOG_KERN |
2974 +---------------+---------------+
2975 | ``lpr`` | LOG_LPR |
2976 +---------------+---------------+
2977 | ``mail`` | LOG_MAIL |
2978 +---------------+---------------+
2979 | ``news`` | LOG_NEWS |
2980 +---------------+---------------+
2981 | ``syslog`` | LOG_SYSLOG |
2982 +---------------+---------------+
2983 | ``user`` | LOG_USER |
2984 +---------------+---------------+
2985 | ``uucp`` | LOG_UUCP |
2986 +---------------+---------------+
2987 | ``local0`` | LOG_LOCAL0 |
2988 +---------------+---------------+
2989 | ``local1`` | LOG_LOCAL1 |
2990 +---------------+---------------+
2991 | ``local2`` | LOG_LOCAL2 |
2992 +---------------+---------------+
2993 | ``local3`` | LOG_LOCAL3 |
2994 +---------------+---------------+
2995 | ``local4`` | LOG_LOCAL4 |
2996 +---------------+---------------+
2997 | ``local5`` | LOG_LOCAL5 |
2998 +---------------+---------------+
2999 | ``local6`` | LOG_LOCAL6 |
3000 +---------------+---------------+
3001 | ``local7`` | LOG_LOCAL7 |
3002 +---------------+---------------+
3003
3004 .. method:: mapPriority(levelname)
3005
3006 Maps a logging level name to a syslog priority name.
3007 You may need to override this if you are using custom levels, or
3008 if the default algorithm is not suitable for your needs. The
3009 default algorithm maps ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and
3010 ``CRITICAL`` to the equivalent syslog names, and all other level
Vinay Sajip9a6b4002010-12-14 19:40:21 +00003011 names to 'warning'.
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00003012
3013.. _nt-eventlog-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00003014
3015NTEventLogHandler
3016^^^^^^^^^^^^^^^^^
3017
3018The :class:`NTEventLogHandler` class, located in the :mod:`logging.handlers`
3019module, supports sending logging messages to a local Windows NT, Windows 2000 or
3020Windows XP event log. Before you can use it, you need Mark Hammond's Win32
3021extensions for Python installed.
3022
3023
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003024.. class:: NTEventLogHandler(appname, dllname=None, logtype='Application')
Georg Brandl116aa622007-08-15 14:28:22 +00003025
3026 Returns a new instance of the :class:`NTEventLogHandler` class. The *appname* is
3027 used to define the application name as it appears in the event log. An
3028 appropriate registry entry is created using this name. The *dllname* should give
3029 the fully qualified pathname of a .dll or .exe which contains message
3030 definitions to hold in the log (if not specified, ``'win32service.pyd'`` is used
3031 - this is installed with the Win32 extensions and contains some basic
3032 placeholder message definitions. Note that use of these placeholders will make
3033 your event logs big, as the entire message source is held in the log. If you
3034 want slimmer logs, you have to pass in the name of your own .dll or .exe which
3035 contains the message definitions you want to use in the event log). The
3036 *logtype* is one of ``'Application'``, ``'System'`` or ``'Security'``, and
3037 defaults to ``'Application'``.
3038
3039
Benjamin Petersone41251e2008-04-25 01:59:09 +00003040 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00003041
Benjamin Petersone41251e2008-04-25 01:59:09 +00003042 At this point, you can remove the application name from the registry as a
3043 source of event log entries. However, if you do this, you will not be able
3044 to see the events as you intended in the Event Log Viewer - it needs to be
3045 able to access the registry to get the .dll name. The current version does
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00003046 not do this.
Georg Brandl116aa622007-08-15 14:28:22 +00003047
3048
Benjamin Petersone41251e2008-04-25 01:59:09 +00003049 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003050
Benjamin Petersone41251e2008-04-25 01:59:09 +00003051 Determines the message ID, event category and event type, and then logs
3052 the message in the NT event log.
Georg Brandl116aa622007-08-15 14:28:22 +00003053
3054
Benjamin Petersone41251e2008-04-25 01:59:09 +00003055 .. method:: getEventCategory(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003056
Benjamin Petersone41251e2008-04-25 01:59:09 +00003057 Returns the event category for the record. Override this if you want to
3058 specify your own categories. This version returns 0.
Georg Brandl116aa622007-08-15 14:28:22 +00003059
3060
Benjamin Petersone41251e2008-04-25 01:59:09 +00003061 .. method:: getEventType(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003062
Benjamin Petersone41251e2008-04-25 01:59:09 +00003063 Returns the event type for the record. Override this if you want to
3064 specify your own types. This version does a mapping using the handler's
3065 typemap attribute, which is set up in :meth:`__init__` to a dictionary
3066 which contains mappings for :const:`DEBUG`, :const:`INFO`,
3067 :const:`WARNING`, :const:`ERROR` and :const:`CRITICAL`. If you are using
3068 your own levels, you will either need to override this method or place a
3069 suitable dictionary in the handler's *typemap* attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00003070
3071
Benjamin Petersone41251e2008-04-25 01:59:09 +00003072 .. method:: getMessageID(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003073
Benjamin Petersone41251e2008-04-25 01:59:09 +00003074 Returns the message ID for the record. If you are using your own messages,
3075 you could do this by having the *msg* passed to the logger being an ID
3076 rather than a format string. Then, in here, you could use a dictionary
3077 lookup to get the message ID. This version returns 1, which is the base
3078 message ID in :file:`win32service.pyd`.
Georg Brandl116aa622007-08-15 14:28:22 +00003079
Vinay Sajipd31f3632010-06-29 15:31:15 +00003080.. _smtp-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00003081
3082SMTPHandler
3083^^^^^^^^^^^
3084
3085The :class:`SMTPHandler` class, located in the :mod:`logging.handlers` module,
3086supports sending logging messages to an email address via SMTP.
3087
3088
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003089.. class:: SMTPHandler(mailhost, fromaddr, toaddrs, subject, credentials=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003090
3091 Returns a new instance of the :class:`SMTPHandler` class. The instance is
3092 initialized with the from and to addresses and subject line of the email. The
3093 *toaddrs* should be a list of strings. To specify a non-standard SMTP port, use
3094 the (host, port) tuple format for the *mailhost* argument. If you use a string,
3095 the standard SMTP port is used. If your SMTP server requires authentication, you
3096 can specify a (username, password) tuple for the *credentials* argument.
3097
Georg Brandl116aa622007-08-15 14:28:22 +00003098
Benjamin Petersone41251e2008-04-25 01:59:09 +00003099 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003100
Benjamin Petersone41251e2008-04-25 01:59:09 +00003101 Formats the record and sends it to the specified addressees.
Georg Brandl116aa622007-08-15 14:28:22 +00003102
3103
Benjamin Petersone41251e2008-04-25 01:59:09 +00003104 .. method:: getSubject(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003105
Benjamin Petersone41251e2008-04-25 01:59:09 +00003106 If you want to specify a subject line which is record-dependent, override
3107 this method.
Georg Brandl116aa622007-08-15 14:28:22 +00003108
Vinay Sajipd31f3632010-06-29 15:31:15 +00003109.. _memory-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00003110
3111MemoryHandler
3112^^^^^^^^^^^^^
3113
3114The :class:`MemoryHandler` class, located in the :mod:`logging.handlers` module,
3115supports buffering of logging records in memory, periodically flushing them to a
3116:dfn:`target` handler. Flushing occurs whenever the buffer is full, or when an
3117event of a certain severity or greater is seen.
3118
3119:class:`MemoryHandler` is a subclass of the more general
3120:class:`BufferingHandler`, which is an abstract class. This buffers logging
3121records in memory. Whenever each record is added to the buffer, a check is made
3122by calling :meth:`shouldFlush` to see if the buffer should be flushed. If it
3123should, then :meth:`flush` is expected to do the needful.
3124
3125
3126.. class:: BufferingHandler(capacity)
3127
3128 Initializes the handler with a buffer of the specified capacity.
3129
3130
Benjamin Petersone41251e2008-04-25 01:59:09 +00003131 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003132
Benjamin Petersone41251e2008-04-25 01:59:09 +00003133 Appends the record to the buffer. If :meth:`shouldFlush` returns true,
3134 calls :meth:`flush` to process the buffer.
Georg Brandl116aa622007-08-15 14:28:22 +00003135
3136
Benjamin Petersone41251e2008-04-25 01:59:09 +00003137 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00003138
Benjamin Petersone41251e2008-04-25 01:59:09 +00003139 You can override this to implement custom flushing behavior. This version
3140 just zaps the buffer to empty.
Georg Brandl116aa622007-08-15 14:28:22 +00003141
3142
Benjamin Petersone41251e2008-04-25 01:59:09 +00003143 .. method:: shouldFlush(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003144
Benjamin Petersone41251e2008-04-25 01:59:09 +00003145 Returns true if the buffer is up to capacity. This method can be
3146 overridden to implement custom flushing strategies.
Georg Brandl116aa622007-08-15 14:28:22 +00003147
3148
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003149.. class:: MemoryHandler(capacity, flushLevel=ERROR, target=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003150
3151 Returns a new instance of the :class:`MemoryHandler` class. The instance is
3152 initialized with a buffer size of *capacity*. If *flushLevel* is not specified,
3153 :const:`ERROR` is used. If no *target* is specified, the target will need to be
3154 set using :meth:`setTarget` before this handler does anything useful.
3155
3156
Benjamin Petersone41251e2008-04-25 01:59:09 +00003157 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00003158
Benjamin Petersone41251e2008-04-25 01:59:09 +00003159 Calls :meth:`flush`, sets the target to :const:`None` and clears the
3160 buffer.
Georg Brandl116aa622007-08-15 14:28:22 +00003161
3162
Benjamin Petersone41251e2008-04-25 01:59:09 +00003163 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00003164
Benjamin Petersone41251e2008-04-25 01:59:09 +00003165 For a :class:`MemoryHandler`, flushing means just sending the buffered
Vinay Sajipc84f0162010-09-21 11:25:39 +00003166 records to the target, if there is one. The buffer is also cleared when
3167 this happens. Override if you want different behavior.
Georg Brandl116aa622007-08-15 14:28:22 +00003168
3169
Benjamin Petersone41251e2008-04-25 01:59:09 +00003170 .. method:: setTarget(target)
Georg Brandl116aa622007-08-15 14:28:22 +00003171
Benjamin Petersone41251e2008-04-25 01:59:09 +00003172 Sets the target handler for this handler.
Georg Brandl116aa622007-08-15 14:28:22 +00003173
3174
Benjamin Petersone41251e2008-04-25 01:59:09 +00003175 .. method:: shouldFlush(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003176
Benjamin Petersone41251e2008-04-25 01:59:09 +00003177 Checks for buffer full or a record at the *flushLevel* or higher.
Georg Brandl116aa622007-08-15 14:28:22 +00003178
3179
Vinay Sajipd31f3632010-06-29 15:31:15 +00003180.. _http-handler:
3181
Georg Brandl116aa622007-08-15 14:28:22 +00003182HTTPHandler
3183^^^^^^^^^^^
3184
3185The :class:`HTTPHandler` class, located in the :mod:`logging.handlers` module,
3186supports sending logging messages to a Web server, using either ``GET`` or
3187``POST`` semantics.
3188
3189
Vinay Sajip1b5646a2010-09-13 20:37:50 +00003190.. class:: HTTPHandler(host, url, method='GET', secure=False, credentials=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003191
Vinay Sajip1b5646a2010-09-13 20:37:50 +00003192 Returns a new instance of the :class:`HTTPHandler` class. The *host* can be
3193 of the form ``host:port``, should you need to use a specific port number.
3194 If no *method* is specified, ``GET`` is used. If *secure* is True, an HTTPS
3195 connection will be used. If *credentials* is specified, it should be a
3196 2-tuple consisting of userid and password, which will be placed in an HTTP
3197 'Authorization' header using Basic authentication. If you specify
3198 credentials, you should also specify secure=True so that your userid and
3199 password are not passed in cleartext across the wire.
Georg Brandl116aa622007-08-15 14:28:22 +00003200
3201
Benjamin Petersone41251e2008-04-25 01:59:09 +00003202 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003203
Senthil Kumaranf0769e82010-08-09 19:53:52 +00003204 Sends the record to the Web server as a percent-encoded dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00003205
3206
Vinay Sajip121a1c42010-09-08 10:46:15 +00003207.. _queue-handler:
3208
3209
3210QueueHandler
3211^^^^^^^^^^^^
3212
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003213.. versionadded:: 3.2
3214
Vinay Sajip121a1c42010-09-08 10:46:15 +00003215The :class:`QueueHandler` class, located in the :mod:`logging.handlers` module,
3216supports sending logging messages to a queue, such as those implemented in the
3217:mod:`queue` or :mod:`multiprocessing` modules.
3218
Vinay Sajip0637d492010-09-23 08:15:54 +00003219Along with the :class:`QueueListener` class, :class:`QueueHandler` can be used
3220to let handlers do their work on a separate thread from the one which does the
3221logging. This is important in Web applications and also other service
3222applications where threads servicing clients need to respond as quickly as
3223possible, while any potentially slow operations (such as sending an email via
3224:class:`SMTPHandler`) are done on a separate thread.
Vinay Sajip121a1c42010-09-08 10:46:15 +00003225
3226.. class:: QueueHandler(queue)
3227
3228 Returns a new instance of the :class:`QueueHandler` class. The instance is
Vinay Sajip63891ed2010-09-13 20:02:39 +00003229 initialized with the queue to send messages to. The queue can be any queue-
Vinay Sajip0637d492010-09-23 08:15:54 +00003230 like object; it's used as-is by the :meth:`enqueue` method, which needs
Vinay Sajip63891ed2010-09-13 20:02:39 +00003231 to know how to send messages to it.
Vinay Sajip121a1c42010-09-08 10:46:15 +00003232
3233
3234 .. method:: emit(record)
3235
Vinay Sajip0258ce82010-09-22 20:34:53 +00003236 Enqueues the result of preparing the LogRecord.
3237
3238 .. method:: prepare(record)
3239
3240 Prepares a record for queuing. The object returned by this
3241 method is enqueued.
3242
3243 The base implementation formats the record to merge the message
3244 and arguments, and removes unpickleable items from the record
3245 in-place.
3246
3247 You might want to override this method if you want to convert
3248 the record to a dict or JSON string, or send a modified copy
3249 of the record while leaving the original intact.
Vinay Sajip121a1c42010-09-08 10:46:15 +00003250
3251 .. method:: enqueue(record)
3252
3253 Enqueues the record on the queue using ``put_nowait()``; you may
3254 want to override this if you want to use blocking behaviour, or a
3255 timeout, or a customised queue implementation.
3256
3257
Vinay Sajip121a1c42010-09-08 10:46:15 +00003258
Vinay Sajip0637d492010-09-23 08:15:54 +00003259.. queue-listener:
3260
3261QueueListener
3262^^^^^^^^^^^^^
3263
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003264.. versionadded:: 3.2
3265
Vinay Sajip0637d492010-09-23 08:15:54 +00003266The :class:`QueueListener` class, located in the :mod:`logging.handlers`
3267module, supports receiving logging messages from a queue, such as those
3268implemented in the :mod:`queue` or :mod:`multiprocessing` modules. The
3269messages are received from a queue in an internal thread and passed, on
Vinay Sajip7292b882010-12-13 18:43:57 +00003270the same thread, to one or more handlers for processing. While
3271:class:`QueueListener` is not itself a handler, it is documented here
3272because it works hand-in-hand with :class:`QueueHandler`.
Vinay Sajip0637d492010-09-23 08:15:54 +00003273
3274Along with the :class:`QueueHandler` class, :class:`QueueListener` can be used
3275to let handlers do their work on a separate thread from the one which does the
3276logging. This is important in Web applications and also other service
3277applications where threads servicing clients need to respond as quickly as
3278possible, while any potentially slow operations (such as sending an email via
3279:class:`SMTPHandler`) are done on a separate thread.
3280
3281.. class:: QueueListener(queue, *handlers)
3282
3283 Returns a new instance of the :class:`QueueListener` class. The instance is
3284 initialized with the queue to send messages to and a list of handlers which
3285 will handle entries placed on the queue. The queue can be any queue-
3286 like object; it's passed as-is to the :meth:`dequeue` method, which needs
3287 to know how to get messages from it.
3288
3289 .. method:: dequeue(block)
3290
3291 Dequeues a record and return it, optionally blocking.
3292
3293 The base implementation uses ``get()``. You may want to override this
3294 method if you want to use timeouts or work with custom queue
3295 implementations.
3296
3297 .. method:: prepare(record)
3298
3299 Prepare a record for handling.
3300
3301 This implementation just returns the passed-in record. You may want to
3302 override this method if you need to do any custom marshalling or
3303 manipulation of the record before passing it to the handlers.
3304
3305 .. method:: handle(record)
3306
3307 Handle a record.
3308
3309 This just loops through the handlers offering them the record
3310 to handle. The actual object passed to the handlers is that which
3311 is returned from :meth:`prepare`.
3312
3313 .. method:: start()
3314
3315 Starts the listener.
3316
3317 This starts up a background thread to monitor the queue for
3318 LogRecords to process.
3319
3320 .. method:: stop()
3321
3322 Stops the listener.
3323
3324 This asks the thread to terminate, and then waits for it to do so.
3325 Note that if you don't call this before your application exits, there
3326 may be some records still left on the queue, which won't be processed.
3327
Vinay Sajip0637d492010-09-23 08:15:54 +00003328
Vinay Sajip63891ed2010-09-13 20:02:39 +00003329.. _zeromq-handlers:
3330
Vinay Sajip0637d492010-09-23 08:15:54 +00003331Subclassing QueueHandler
3332^^^^^^^^^^^^^^^^^^^^^^^^
3333
Vinay Sajip63891ed2010-09-13 20:02:39 +00003334You can use a :class:`QueueHandler` subclass to send messages to other kinds
Vinay Sajip9a6b4002010-12-14 19:40:21 +00003335of queues, for example a ZeroMQ 'publish' socket. In the example below,the
Vinay Sajip63891ed2010-09-13 20:02:39 +00003336socket is created separately and passed to the handler (as its 'queue')::
3337
3338 import zmq # using pyzmq, the Python binding for ZeroMQ
3339 import json # for serializing records portably
3340
3341 ctx = zmq.Context()
3342 sock = zmq.Socket(ctx, zmq.PUB) # or zmq.PUSH, or other suitable value
3343 sock.bind('tcp://*:5556') # or wherever
3344
3345 class ZeroMQSocketHandler(QueueHandler):
3346 def enqueue(self, record):
3347 data = json.dumps(record.__dict__)
3348 self.queue.send(data)
3349
Vinay Sajip0055c422010-09-14 09:42:39 +00003350 handler = ZeroMQSocketHandler(sock)
3351
3352
Vinay Sajip63891ed2010-09-13 20:02:39 +00003353Of course there are other ways of organizing this, for example passing in the
3354data needed by the handler to create the socket::
3355
3356 class ZeroMQSocketHandler(QueueHandler):
3357 def __init__(self, uri, socktype=zmq.PUB, ctx=None):
3358 self.ctx = ctx or zmq.Context()
3359 socket = zmq.Socket(self.ctx, socktype)
Vinay Sajip0637d492010-09-23 08:15:54 +00003360 socket.bind(uri)
Vinay Sajip0055c422010-09-14 09:42:39 +00003361 QueueHandler.__init__(self, socket)
Vinay Sajip63891ed2010-09-13 20:02:39 +00003362
3363 def enqueue(self, record):
3364 data = json.dumps(record.__dict__)
3365 self.queue.send(data)
3366
Vinay Sajipde726922010-09-14 06:59:24 +00003367 def close(self):
3368 self.queue.close()
Vinay Sajip121a1c42010-09-08 10:46:15 +00003369
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003370
Vinay Sajip0637d492010-09-23 08:15:54 +00003371Subclassing QueueListener
3372^^^^^^^^^^^^^^^^^^^^^^^^^
3373
3374You can also subclass :class:`QueueListener` to get messages from other kinds
Vinay Sajip9a6b4002010-12-14 19:40:21 +00003375of queues, for example a ZeroMQ 'subscribe' socket. Here's an example::
Vinay Sajip0637d492010-09-23 08:15:54 +00003376
3377 class ZeroMQSocketListener(QueueListener):
3378 def __init__(self, uri, *handlers, **kwargs):
3379 self.ctx = kwargs.get('ctx') or zmq.Context()
3380 socket = zmq.Socket(self.ctx, zmq.SUB)
3381 socket.setsockopt(zmq.SUBSCRIBE, '') # subscribe to everything
3382 socket.connect(uri)
3383
3384 def dequeue(self):
3385 msg = self.queue.recv()
3386 return logging.makeLogRecord(json.loads(msg))
3387
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003388
Christian Heimes8b0facf2007-12-04 19:30:01 +00003389.. _formatter-objects:
3390
Georg Brandl116aa622007-08-15 14:28:22 +00003391Formatter Objects
3392-----------------
3393
Benjamin Peterson75edad02009-01-01 15:05:06 +00003394.. currentmodule:: logging
3395
Vinay Sajip7292b882010-12-13 18:43:57 +00003396:class:`Formatter` objects have the following attributes and methods. They are
Georg Brandl116aa622007-08-15 14:28:22 +00003397responsible for converting a :class:`LogRecord` to (usually) a string which can
3398be interpreted by either a human or an external system. The base
3399:class:`Formatter` allows a formatting string to be specified. If none is
3400supplied, the default value of ``'%(message)s'`` is used.
3401
3402A Formatter can be initialized with a format string which makes use of knowledge
3403of the :class:`LogRecord` attributes - such as the default value mentioned above
3404making use of the fact that the user's message and arguments are pre-formatted
3405into a :class:`LogRecord`'s *message* attribute. This format string contains
Ezio Melotti0639d5a2009-12-19 23:26:38 +00003406standard Python %-style mapping keys. See section :ref:`old-string-formatting`
Georg Brandl116aa622007-08-15 14:28:22 +00003407for more information on string formatting.
3408
Vinay Sajip7292b882010-12-13 18:43:57 +00003409The useful mapping keys in a :class:`LogRecord` are given in the section on
3410:ref:`logrecord-attributes`.
Georg Brandl116aa622007-08-15 14:28:22 +00003411
Georg Brandl116aa622007-08-15 14:28:22 +00003412
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003413.. class:: Formatter(fmt=None, datefmt=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003414
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003415 Returns a new instance of the :class:`Formatter` class. The instance is
3416 initialized with a format string for the message as a whole, as well as a
3417 format string for the date/time portion of a message. If no *fmt* is
3418 specified, ``'%(message)s'`` is used. If no *datefmt* is specified, the
3419 ISO8601 date format is used.
Georg Brandl116aa622007-08-15 14:28:22 +00003420
Benjamin Petersone41251e2008-04-25 01:59:09 +00003421 .. method:: format(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003422
Benjamin Petersone41251e2008-04-25 01:59:09 +00003423 The record's attribute dictionary is used as the operand to a string
3424 formatting operation. Returns the resulting string. Before formatting the
3425 dictionary, a couple of preparatory steps are carried out. The *message*
3426 attribute of the record is computed using *msg* % *args*. If the
3427 formatting string contains ``'(asctime)'``, :meth:`formatTime` is called
3428 to format the event time. If there is exception information, it is
3429 formatted using :meth:`formatException` and appended to the message. Note
3430 that the formatted exception information is cached in attribute
3431 *exc_text*. This is useful because the exception information can be
3432 pickled and sent across the wire, but you should be careful if you have
3433 more than one :class:`Formatter` subclass which customizes the formatting
3434 of exception information. In this case, you will have to clear the cached
3435 value after a formatter has done its formatting, so that the next
3436 formatter to handle the event doesn't use the cached value but
3437 recalculates it afresh.
Georg Brandl116aa622007-08-15 14:28:22 +00003438
Vinay Sajip8593ae62010-11-14 21:33:04 +00003439 If stack information is available, it's appended after the exception
3440 information, using :meth:`formatStack` to transform it if necessary.
3441
Georg Brandl116aa622007-08-15 14:28:22 +00003442
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003443 .. method:: formatTime(record, datefmt=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003444
Benjamin Petersone41251e2008-04-25 01:59:09 +00003445 This method should be called from :meth:`format` by a formatter which
3446 wants to make use of a formatted time. This method can be overridden in
3447 formatters to provide for any specific requirement, but the basic behavior
3448 is as follows: if *datefmt* (a string) is specified, it is used with
3449 :func:`time.strftime` to format the creation time of the
3450 record. Otherwise, the ISO8601 format is used. The resulting string is
3451 returned.
Georg Brandl116aa622007-08-15 14:28:22 +00003452
3453
Benjamin Petersone41251e2008-04-25 01:59:09 +00003454 .. method:: formatException(exc_info)
Georg Brandl116aa622007-08-15 14:28:22 +00003455
Benjamin Petersone41251e2008-04-25 01:59:09 +00003456 Formats the specified exception information (a standard exception tuple as
3457 returned by :func:`sys.exc_info`) as a string. This default implementation
3458 just uses :func:`traceback.print_exception`. The resulting string is
3459 returned.
Georg Brandl116aa622007-08-15 14:28:22 +00003460
Vinay Sajip8593ae62010-11-14 21:33:04 +00003461 .. method:: formatStack(stack_info)
3462
3463 Formats the specified stack information (a string as returned by
3464 :func:`traceback.print_stack`, but with the last newline removed) as a
3465 string. This default implementation just returns the input value.
3466
Vinay Sajipd31f3632010-06-29 15:31:15 +00003467.. _filter:
Georg Brandl116aa622007-08-15 14:28:22 +00003468
3469Filter Objects
3470--------------
3471
Georg Brandl5c66bca2010-10-29 05:36:28 +00003472``Filters`` can be used by ``Handlers`` and ``Loggers`` for more sophisticated
Vinay Sajipfc082ca2010-10-19 21:13:49 +00003473filtering than is provided by levels. The base filter class only allows events
3474which are below a certain point in the logger hierarchy. For example, a filter
Vinay Sajip9a6b4002010-12-14 19:40:21 +00003475initialized with 'A.B' will allow events logged by loggers 'A.B', 'A.B.C',
3476'A.B.C.D', 'A.B.D' etc. but not 'A.BB', 'B.A.B' etc. If initialized with the
Vinay Sajipfc082ca2010-10-19 21:13:49 +00003477empty string, all events are passed.
Georg Brandl116aa622007-08-15 14:28:22 +00003478
3479
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003480.. class:: Filter(name='')
Georg Brandl116aa622007-08-15 14:28:22 +00003481
3482 Returns an instance of the :class:`Filter` class. If *name* is specified, it
3483 names a logger which, together with its children, will have its events allowed
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003484 through the filter. If *name* is the empty string, allows every event.
Georg Brandl116aa622007-08-15 14:28:22 +00003485
3486
Benjamin Petersone41251e2008-04-25 01:59:09 +00003487 .. method:: filter(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003488
Benjamin Petersone41251e2008-04-25 01:59:09 +00003489 Is the specified record to be logged? Returns zero for no, nonzero for
3490 yes. If deemed appropriate, the record may be modified in-place by this
3491 method.
Georg Brandl116aa622007-08-15 14:28:22 +00003492
Vinay Sajip81010212010-08-19 19:17:41 +00003493Note that filters attached to handlers are consulted whenever an event is
3494emitted by the handler, whereas filters attached to loggers are consulted
3495whenever an event is logged to the handler (using :meth:`debug`, :meth:`info`,
3496etc.) This means that events which have been generated by descendant loggers
3497will not be filtered by a logger's filter setting, unless the filter has also
3498been applied to those descendant loggers.
3499
Vinay Sajip22246fd2010-10-20 11:40:02 +00003500You don't actually need to subclass ``Filter``: you can pass any instance
3501which has a ``filter`` method with the same semantics.
3502
Vinay Sajipfc082ca2010-10-19 21:13:49 +00003503.. versionchanged:: 3.2
Vinay Sajip05ed6952010-10-20 20:34:09 +00003504 You don't need to create specialized ``Filter`` classes, or use other
3505 classes with a ``filter`` method: you can use a function (or other
3506 callable) as a filter. The filtering logic will check to see if the filter
3507 object has a ``filter`` attribute: if it does, it's assumed to be a
3508 ``Filter`` and its :meth:`~Filter.filter` method is called. Otherwise, it's
3509 assumed to be a callable and called with the record as the single
3510 parameter. The returned value should conform to that returned by
3511 :meth:`~Filter.filter`.
Vinay Sajipfc082ca2010-10-19 21:13:49 +00003512
Vinay Sajipac007992010-09-17 12:45:26 +00003513Other uses for filters
3514^^^^^^^^^^^^^^^^^^^^^^
3515
3516Although filters are used primarily to filter records based on more
3517sophisticated criteria than levels, they get to see every record which is
3518processed by the handler or logger they're attached to: this can be useful if
3519you want to do things like counting how many records were processed by a
3520particular logger or handler, or adding, changing or removing attributes in
3521the LogRecord being processed. Obviously changing the LogRecord needs to be
3522done with some care, but it does allow the injection of contextual information
3523into logs (see :ref:`filters-contextual`).
3524
Vinay Sajipd31f3632010-06-29 15:31:15 +00003525.. _log-record:
Georg Brandl116aa622007-08-15 14:28:22 +00003526
3527LogRecord Objects
3528-----------------
3529
Vinay Sajip4039aff2010-09-11 10:25:28 +00003530:class:`LogRecord` instances are created automatically by the :class:`Logger`
3531every time something is logged, and can be created manually via
3532:func:`makeLogRecord` (for example, from a pickled event received over the
3533wire).
Georg Brandl116aa622007-08-15 14:28:22 +00003534
3535
Vinay Sajip7292b882010-12-13 18:43:57 +00003536.. class:: LogRecord(name, level, pathname, lineno, msg, args, exc_info, func=None, sinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003537
Vinay Sajip4039aff2010-09-11 10:25:28 +00003538 Contains all the information pertinent to the event being logged.
Georg Brandl116aa622007-08-15 14:28:22 +00003539
Vinay Sajip4039aff2010-09-11 10:25:28 +00003540 The primary information is passed in :attr:`msg` and :attr:`args`, which
3541 are combined using ``msg % args`` to create the :attr:`message` field of the
3542 record.
3543
Vinay Sajip7292b882010-12-13 18:43:57 +00003544 :param name: The name of the logger used to log the event represented by
3545 this LogRecord.
3546 :param level: The numeric level of the logging event (one of DEBUG, INFO etc.)
3547 :param pathname: The full pathname of the source file where the logging call
3548 was made.
3549 :param lineno: The line number in the source file where the logging call was
3550 made.
3551 :param msg: The event description message, possibly a format string with
3552 placeholders for variable data.
3553 :param args: Variable data to merge into the *msg* argument to obtain the
3554 event description.
3555 :param exc_info: An exception tuple with the current exception information,
3556 or *None* if no exception information is available.
3557 :param func: The name of the function or method from which the logging call
3558 was invoked.
3559 :param sinfo: A text string representing stack information from the base of
3560 the stack in the current thread, up to the logging call.
Vinay Sajip8593ae62010-11-14 21:33:04 +00003561
Benjamin Petersone41251e2008-04-25 01:59:09 +00003562 .. method:: getMessage()
Georg Brandl116aa622007-08-15 14:28:22 +00003563
Benjamin Petersone41251e2008-04-25 01:59:09 +00003564 Returns the message for this :class:`LogRecord` instance after merging any
Vinay Sajip4039aff2010-09-11 10:25:28 +00003565 user-supplied arguments with the message. If the user-supplied message
3566 argument to the logging call is not a string, :func:`str` is called on it to
3567 convert it to a string. This allows use of user-defined classes as
3568 messages, whose ``__str__`` method can return the actual format string to
3569 be used.
3570
Vinay Sajip61561522010-12-03 11:50:38 +00003571 .. versionchanged:: 3.2
3572 The creation of a ``LogRecord`` has been made more configurable by
3573 providing a factory which is used to create the record. The factory can be
3574 set using :func:`getLogRecordFactory` and :func:`setLogRecordFactory`
3575 (see this for the factory's signature).
3576
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003577 This functionality can be used to inject your own values into a
3578 LogRecord at creation time. You can use the following pattern::
Vinay Sajip61561522010-12-03 11:50:38 +00003579
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003580 old_factory = logging.getLogRecordFactory()
Vinay Sajip61561522010-12-03 11:50:38 +00003581
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003582 def record_factory(*args, **kwargs):
3583 record = old_factory(*args, **kwargs)
3584 record.custom_attribute = 0xdecafbad
3585 return record
Vinay Sajip61561522010-12-03 11:50:38 +00003586
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003587 logging.setLogRecordFactory(record_factory)
Vinay Sajip61561522010-12-03 11:50:38 +00003588
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003589 With this pattern, multiple factories could be chained, and as long
3590 as they don't overwrite each other's attributes or unintentionally
3591 overwrite the standard attributes listed above, there should be no
3592 surprises.
3593
Vinay Sajip61561522010-12-03 11:50:38 +00003594
Vinay Sajip7292b882010-12-13 18:43:57 +00003595.. _logrecord-attributes:
3596
3597``LogRecord`` attributes
3598^^^^^^^^^^^^^^^^^^^^^^^^
3599
3600The LogRecord has a number of attributes, most of which are derived from the
3601parameters to the constructor. (Note that the names do not always correspond
3602exactly between the LogRecord constructor parameters and the LogRecord
3603attributes.) These attributes can be used to merge data from the record into
3604the format string. The following table lists (in alphabetical order) the
3605attribute names, their meanings and the corresponding placeholder in a %-style
3606format string.
3607
3608If you are using {}-formatting (:func:`str.format`), you can use
Vinay Sajipfd94b172010-12-13 18:49:08 +00003609``{attrname}`` as the placeholder in the format string. If you are using
Vinay Sajip7292b882010-12-13 18:43:57 +00003610$-formatting (:class:`string.Template`), use the form ``${attrname}``. In
3611both cases, of course, replace ``attrname`` with the actual attribute name
3612you want to use.
3613
3614In the case of {}-formatting, you can specify formatting flags by placing them
Vinay Sajipfd94b172010-12-13 18:49:08 +00003615after the attribute name, separated from it with a colon. For example: a
3616placeholder of ``{msecs:03d}`` would format a millisecond value of ``4`` as
3617``004``. Refer to the :meth:`str.format` documentation for full details on
3618the options available to you.
Vinay Sajip7292b882010-12-13 18:43:57 +00003619
3620+----------------+-------------------------+-----------------------------------------------+
3621| Attribute name | Format | Description |
3622+================+=========================+===============================================+
3623| args | You shouldn't need to | The tuple of arguments merged into ``msg`` to |
3624| | format this yourself. | produce ``message``. |
3625+----------------+-------------------------+-----------------------------------------------+
3626| asctime | ``%(asctime)s`` | Human-readable time when the |
3627| | | :class:`LogRecord` was created. By default |
Vinay Sajip9a6b4002010-12-14 19:40:21 +00003628| | | this is of the form '2003-07-08 16:49:45,896' |
Vinay Sajip7292b882010-12-13 18:43:57 +00003629| | | (the numbers after the comma are millisecond |
3630| | | portion of the time). |
3631+----------------+-------------------------+-----------------------------------------------+
3632| created | ``%(created)f`` | Time when the :class:`LogRecord` was created |
3633| | | (as returned by :func:`time.time`). |
3634+----------------+-------------------------+-----------------------------------------------+
3635| exc_info | You shouldn't need to | Exception tuple (à la ``sys.exc_info``) or, |
3636| | format this yourself. | if no exception has occurred, *None*. |
3637+----------------+-------------------------+-----------------------------------------------+
3638| filename | ``%(filename)s`` | Filename portion of ``pathname``. |
3639+----------------+-------------------------+-----------------------------------------------+
3640| funcName | ``%(funcName)s`` | Name of function containing the logging call. |
3641+----------------+-------------------------+-----------------------------------------------+
3642| levelname | ``%(levelname)s`` | Text logging level for the message |
3643| | | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
3644| | | ``'ERROR'``, ``'CRITICAL'``). |
3645+----------------+-------------------------+-----------------------------------------------+
3646| levelno | ``%(levelno)s`` | Numeric logging level for the message |
3647| | | (:const:`DEBUG`, :const:`INFO`, |
3648| | | :const:`WARNING`, :const:`ERROR`, |
3649| | | :const:`CRITICAL`). |
3650+----------------+-------------------------+-----------------------------------------------+
3651| lineno | ``%(lineno)d`` | Source line number where the logging call was |
3652| | | issued (if available). |
3653+----------------+-------------------------+-----------------------------------------------+
3654| module | ``%(module)s`` | Module (name portion of ``filename``). |
3655+----------------+-------------------------+-----------------------------------------------+
3656| msecs | ``%(msecs)d`` | Millisecond portion of the time when the |
3657| | | :class:`LogRecord` was created. |
3658+----------------+-------------------------+-----------------------------------------------+
3659| message | ``%(message)s`` | The logged message, computed as ``msg % |
3660| | | args``. This is set when |
3661| | | :meth:`Formatter.format` is invoked. |
3662+----------------+-------------------------+-----------------------------------------------+
3663| msg | You shouldn't need to | The format string passed in the original |
3664| | format this yourself. | logging call. Merged with ``args`` to |
3665| | | produce ``message``, or an arbitrary object |
3666| | | (see :ref:`arbitrary-object-messages`). |
3667+----------------+-------------------------+-----------------------------------------------+
3668| name | ``%(name)s`` | Name of the logger used to log the call. |
3669+----------------+-------------------------+-----------------------------------------------+
3670| pathname | ``%(pathname)s`` | Full pathname of the source file where the |
3671| | | logging call was issued (if available). |
3672+----------------+-------------------------+-----------------------------------------------+
3673| process | ``%(process)d`` | Process ID (if available). |
3674+----------------+-------------------------+-----------------------------------------------+
3675| processName | ``%(processName)s`` | Process name (if available). |
3676+----------------+-------------------------+-----------------------------------------------+
3677| relativeCreated| ``%(relativeCreated)d`` | Time in milliseconds when the LogRecord was |
3678| | | created, relative to the time the logging |
3679| | | module was loaded. |
3680+----------------+-------------------------+-----------------------------------------------+
3681| stack_info | You shouldn't need to | Stack frame information (where available) |
3682| | format this yourself. | from the bottom of the stack in the current |
3683| | | thread, up to and including the stack frame |
3684| | | of the logging call which resulted in the |
3685| | | creation of this record. |
3686+----------------+-------------------------+-----------------------------------------------+
3687| thread | ``%(thread)d`` | Thread ID (if available). |
3688+----------------+-------------------------+-----------------------------------------------+
3689| threadName | ``%(threadName)s`` | Thread name (if available). |
3690+----------------+-------------------------+-----------------------------------------------+
3691
3692
Vinay Sajipd31f3632010-06-29 15:31:15 +00003693.. _logger-adapter:
Georg Brandl116aa622007-08-15 14:28:22 +00003694
Christian Heimes04c420f2008-01-18 18:40:46 +00003695LoggerAdapter Objects
3696---------------------
3697
Christian Heimes04c420f2008-01-18 18:40:46 +00003698:class:`LoggerAdapter` instances are used to conveniently pass contextual
Georg Brandl86def6c2008-01-21 20:36:10 +00003699information into logging calls. For a usage example , see the section on
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003700:ref:`adding contextual information to your logging output <context-info>`.
Georg Brandl86def6c2008-01-21 20:36:10 +00003701
Christian Heimes04c420f2008-01-18 18:40:46 +00003702
3703.. class:: LoggerAdapter(logger, extra)
3704
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003705 Returns an instance of :class:`LoggerAdapter` initialized with an
3706 underlying :class:`Logger` instance and a dict-like object.
Christian Heimes04c420f2008-01-18 18:40:46 +00003707
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003708 .. method:: process(msg, kwargs)
Christian Heimes04c420f2008-01-18 18:40:46 +00003709
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003710 Modifies the message and/or keyword arguments passed to a logging call in
3711 order to insert contextual information. This implementation takes the object
3712 passed as *extra* to the constructor and adds it to *kwargs* using key
3713 'extra'. The return value is a (*msg*, *kwargs*) tuple which has the
3714 (possibly modified) versions of the arguments passed in.
Christian Heimes04c420f2008-01-18 18:40:46 +00003715
Vinay Sajipc84f0162010-09-21 11:25:39 +00003716In addition to the above, :class:`LoggerAdapter` supports the following
Christian Heimes04c420f2008-01-18 18:40:46 +00003717methods of :class:`Logger`, i.e. :meth:`debug`, :meth:`info`, :meth:`warning`,
Vinay Sajipc84f0162010-09-21 11:25:39 +00003718:meth:`error`, :meth:`exception`, :meth:`critical`, :meth:`log`,
3719:meth:`isEnabledFor`, :meth:`getEffectiveLevel`, :meth:`setLevel`,
3720:meth:`hasHandlers`. These methods have the same signatures as their
3721counterparts in :class:`Logger`, so you can use the two types of instances
3722interchangeably.
Christian Heimes04c420f2008-01-18 18:40:46 +00003723
Ezio Melotti4d5195b2010-04-20 10:57:44 +00003724.. versionchanged:: 3.2
Vinay Sajipc84f0162010-09-21 11:25:39 +00003725 The :meth:`isEnabledFor`, :meth:`getEffectiveLevel`, :meth:`setLevel` and
3726 :meth:`hasHandlers` methods were added to :class:`LoggerAdapter`. These
3727 methods delegate to the underlying logger.
Benjamin Peterson22005fc2010-04-11 16:25:06 +00003728
Georg Brandl116aa622007-08-15 14:28:22 +00003729
3730Thread Safety
3731-------------
3732
3733The logging module is intended to be thread-safe without any special work
3734needing to be done by its clients. It achieves this though using threading
3735locks; there is one lock to serialize access to the module's shared data, and
3736each handler also creates a lock to serialize access to its underlying I/O.
3737
Benjamin Petersond23f8222009-04-05 19:13:16 +00003738If you are implementing asynchronous signal handlers using the :mod:`signal`
3739module, you may not be able to use logging from within such handlers. This is
3740because lock implementations in the :mod:`threading` module are not always
3741re-entrant, and so cannot be invoked from such signal handlers.
Georg Brandl116aa622007-08-15 14:28:22 +00003742
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00003743
3744Integration with the warnings module
3745------------------------------------
3746
3747The :func:`captureWarnings` function can be used to integrate :mod:`logging`
3748with the :mod:`warnings` module.
3749
3750.. function:: captureWarnings(capture)
3751
3752 This function is used to turn the capture of warnings by logging on and
3753 off.
3754
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003755 If *capture* is ``True``, warnings issued by the :mod:`warnings` module will
3756 be redirected to the logging system. Specifically, a warning will be
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00003757 formatted using :func:`warnings.formatwarning` and the resulting string
Vinay Sajip9a6b4002010-12-14 19:40:21 +00003758 logged to a logger named 'py.warnings' with a severity of `WARNING`.
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00003759
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003760 If *capture* is ``False``, the redirection of warnings to the logging system
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00003761 will stop, and warnings will be redirected to their original destinations
3762 (i.e. those in effect before `captureWarnings(True)` was called).
3763
3764
Vinay Sajip75043022010-12-19 06:02:31 +00003765.. _config-ref:
3766
Georg Brandl116aa622007-08-15 14:28:22 +00003767Configuration
3768-------------
3769
3770
3771.. _logging-config-api:
3772
3773Configuration functions
3774^^^^^^^^^^^^^^^^^^^^^^^
3775
Georg Brandl116aa622007-08-15 14:28:22 +00003776The following functions configure the logging module. They are located in the
3777:mod:`logging.config` module. Their use is optional --- you can configure the
3778logging module using these functions or by making calls to the main API (defined
3779in :mod:`logging` itself) and defining handlers which are declared either in
3780:mod:`logging` or :mod:`logging.handlers`.
3781
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003782.. function:: dictConfig(config)
Georg Brandl116aa622007-08-15 14:28:22 +00003783
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003784 Takes the logging configuration from a dictionary. The contents of
3785 this dictionary are described in :ref:`logging-config-dictschema`
3786 below.
3787
3788 If an error is encountered during configuration, this function will
3789 raise a :exc:`ValueError`, :exc:`TypeError`, :exc:`AttributeError`
3790 or :exc:`ImportError` with a suitably descriptive message. The
3791 following is a (possibly incomplete) list of conditions which will
3792 raise an error:
3793
3794 * A ``level`` which is not a string or which is a string not
3795 corresponding to an actual logging level.
3796 * A ``propagate`` value which is not a boolean.
3797 * An id which does not have a corresponding destination.
3798 * A non-existent handler id found during an incremental call.
3799 * An invalid logger name.
3800 * Inability to resolve to an internal or external object.
3801
3802 Parsing is performed by the :class:`DictConfigurator` class, whose
3803 constructor is passed the dictionary used for configuration, and
3804 has a :meth:`configure` method. The :mod:`logging.config` module
3805 has a callable attribute :attr:`dictConfigClass`
3806 which is initially set to :class:`DictConfigurator`.
3807 You can replace the value of :attr:`dictConfigClass` with a
3808 suitable implementation of your own.
3809
3810 :func:`dictConfig` calls :attr:`dictConfigClass` passing
3811 the specified dictionary, and then calls the :meth:`configure` method on
3812 the returned object to put the configuration into effect::
3813
3814 def dictConfig(config):
3815 dictConfigClass(config).configure()
3816
3817 For example, a subclass of :class:`DictConfigurator` could call
3818 ``DictConfigurator.__init__()`` in its own :meth:`__init__()`, then
3819 set up custom prefixes which would be usable in the subsequent
3820 :meth:`configure` call. :attr:`dictConfigClass` would be bound to
3821 this new subclass, and then :func:`dictConfig` could be called exactly as
3822 in the default, uncustomized state.
3823
3824.. function:: fileConfig(fname[, defaults])
Georg Brandl116aa622007-08-15 14:28:22 +00003825
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00003826 Reads the logging configuration from a :mod:`configparser`\-format file named
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00003827 *fname*. This function can be called several times from an application,
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003828 allowing an end user to select from various pre-canned
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00003829 configurations (if the developer provides a mechanism to present the choices
3830 and load the chosen configuration). Defaults to be passed to the ConfigParser
3831 can be specified in the *defaults* argument.
Georg Brandl116aa622007-08-15 14:28:22 +00003832
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003833
3834.. function:: listen(port=DEFAULT_LOGGING_CONFIG_PORT)
Georg Brandl116aa622007-08-15 14:28:22 +00003835
3836 Starts up a socket server on the specified port, and listens for new
3837 configurations. If no port is specified, the module's default
3838 :const:`DEFAULT_LOGGING_CONFIG_PORT` is used. Logging configurations will be
3839 sent as a file suitable for processing by :func:`fileConfig`. Returns a
3840 :class:`Thread` instance on which you can call :meth:`start` to start the
3841 server, and which you can :meth:`join` when appropriate. To stop the server,
Christian Heimes8b0facf2007-12-04 19:30:01 +00003842 call :func:`stopListening`.
3843
3844 To send a configuration to the socket, read in the configuration file and
3845 send it to the socket as a string of bytes preceded by a four-byte length
3846 string packed in binary using ``struct.pack('>L', n)``.
Georg Brandl116aa622007-08-15 14:28:22 +00003847
3848
3849.. function:: stopListening()
3850
Christian Heimes8b0facf2007-12-04 19:30:01 +00003851 Stops the listening server which was created with a call to :func:`listen`.
3852 This is typically called before calling :meth:`join` on the return value from
Georg Brandl116aa622007-08-15 14:28:22 +00003853 :func:`listen`.
3854
3855
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003856.. _logging-config-dictschema:
3857
3858Configuration dictionary schema
3859^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3860
3861Describing a logging configuration requires listing the various
3862objects to create and the connections between them; for example, you
Vinay Sajip9a6b4002010-12-14 19:40:21 +00003863may create a handler named 'console' and then say that the logger
3864named 'startup' will send its messages to the 'console' handler.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003865These objects aren't limited to those provided by the :mod:`logging`
3866module because you might write your own formatter or handler class.
3867The parameters to these classes may also need to include external
3868objects such as ``sys.stderr``. The syntax for describing these
3869objects and connections is defined in :ref:`logging-config-dict-connections`
3870below.
3871
3872Dictionary Schema Details
3873"""""""""""""""""""""""""
3874
3875The dictionary passed to :func:`dictConfig` must contain the following
3876keys:
3877
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003878* *version* - to be set to an integer value representing the schema
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003879 version. The only valid value at present is 1, but having this key
3880 allows the schema to evolve while still preserving backwards
3881 compatibility.
3882
3883All other keys are optional, but if present they will be interpreted
3884as described below. In all cases below where a 'configuring dict' is
3885mentioned, it will be checked for the special ``'()'`` key to see if a
3886custom instantiation is required. If so, the mechanism described in
3887:ref:`logging-config-dict-userdef` below is used to create an instance;
3888otherwise, the context is used to determine what to instantiate.
3889
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003890* *formatters* - the corresponding value will be a dict in which each
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003891 key is a formatter id and each value is a dict describing how to
3892 configure the corresponding Formatter instance.
3893
3894 The configuring dict is searched for keys ``format`` and ``datefmt``
3895 (with defaults of ``None``) and these are used to construct a
3896 :class:`logging.Formatter` instance.
3897
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003898* *filters* - the corresponding value will be a dict in which each key
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003899 is a filter id and each value is a dict describing how to configure
3900 the corresponding Filter instance.
3901
3902 The configuring dict is searched for the key ``name`` (defaulting to the
3903 empty string) and this is used to construct a :class:`logging.Filter`
3904 instance.
3905
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003906* *handlers* - the corresponding value will be a dict in which each
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003907 key is a handler id and each value is a dict describing how to
3908 configure the corresponding Handler instance.
3909
3910 The configuring dict is searched for the following keys:
3911
3912 * ``class`` (mandatory). This is the fully qualified name of the
3913 handler class.
3914
3915 * ``level`` (optional). The level of the handler.
3916
3917 * ``formatter`` (optional). The id of the formatter for this
3918 handler.
3919
3920 * ``filters`` (optional). A list of ids of the filters for this
3921 handler.
3922
3923 All *other* keys are passed through as keyword arguments to the
3924 handler's constructor. For example, given the snippet::
3925
3926 handlers:
3927 console:
3928 class : logging.StreamHandler
3929 formatter: brief
3930 level : INFO
3931 filters: [allow_foo]
3932 stream : ext://sys.stdout
3933 file:
3934 class : logging.handlers.RotatingFileHandler
3935 formatter: precise
3936 filename: logconfig.log
3937 maxBytes: 1024
3938 backupCount: 3
3939
3940 the handler with id ``console`` is instantiated as a
3941 :class:`logging.StreamHandler`, using ``sys.stdout`` as the underlying
3942 stream. The handler with id ``file`` is instantiated as a
3943 :class:`logging.handlers.RotatingFileHandler` with the keyword arguments
3944 ``filename='logconfig.log', maxBytes=1024, backupCount=3``.
3945
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003946* *loggers* - the corresponding value will be a dict in which each key
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003947 is a logger name and each value is a dict describing how to
3948 configure the corresponding Logger instance.
3949
3950 The configuring dict is searched for the following keys:
3951
3952 * ``level`` (optional). The level of the logger.
3953
3954 * ``propagate`` (optional). The propagation setting of the logger.
3955
3956 * ``filters`` (optional). A list of ids of the filters for this
3957 logger.
3958
3959 * ``handlers`` (optional). A list of ids of the handlers for this
3960 logger.
3961
3962 The specified loggers will be configured according to the level,
3963 propagation, filters and handlers specified.
3964
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003965* *root* - this will be the configuration for the root logger.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003966 Processing of the configuration will be as for any logger, except
3967 that the ``propagate`` setting will not be applicable.
3968
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003969* *incremental* - whether the configuration is to be interpreted as
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003970 incremental to the existing configuration. This value defaults to
3971 ``False``, which means that the specified configuration replaces the
3972 existing configuration with the same semantics as used by the
3973 existing :func:`fileConfig` API.
3974
3975 If the specified value is ``True``, the configuration is processed
3976 as described in the section on :ref:`logging-config-dict-incremental`.
3977
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003978* *disable_existing_loggers* - whether any existing loggers are to be
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003979 disabled. This setting mirrors the parameter of the same name in
3980 :func:`fileConfig`. If absent, this parameter defaults to ``True``.
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003981 This value is ignored if *incremental* is ``True``.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003982
3983.. _logging-config-dict-incremental:
3984
3985Incremental Configuration
3986"""""""""""""""""""""""""
3987
3988It is difficult to provide complete flexibility for incremental
3989configuration. For example, because objects such as filters
3990and formatters are anonymous, once a configuration is set up, it is
3991not possible to refer to such anonymous objects when augmenting a
3992configuration.
3993
3994Furthermore, there is not a compelling case for arbitrarily altering
3995the object graph of loggers, handlers, filters, formatters at
3996run-time, once a configuration is set up; the verbosity of loggers and
3997handlers can be controlled just by setting levels (and, in the case of
3998loggers, propagation flags). Changing the object graph arbitrarily in
3999a safe way is problematic in a multi-threaded environment; while not
4000impossible, the benefits are not worth the complexity it adds to the
4001implementation.
4002
4003Thus, when the ``incremental`` key of a configuration dict is present
4004and is ``True``, the system will completely ignore any ``formatters`` and
4005``filters`` entries, and process only the ``level``
4006settings in the ``handlers`` entries, and the ``level`` and
4007``propagate`` settings in the ``loggers`` and ``root`` entries.
4008
4009Using a value in the configuration dict lets configurations to be sent
4010over the wire as pickled dicts to a socket listener. Thus, the logging
4011verbosity of a long-running application can be altered over time with
4012no need to stop and restart the application.
4013
4014.. _logging-config-dict-connections:
4015
4016Object connections
4017""""""""""""""""""
4018
4019The schema describes a set of logging objects - loggers,
4020handlers, formatters, filters - which are connected to each other in
4021an object graph. Thus, the schema needs to represent connections
4022between the objects. For example, say that, once configured, a
4023particular logger has attached to it a particular handler. For the
4024purposes of this discussion, we can say that the logger represents the
4025source, and the handler the destination, of a connection between the
4026two. Of course in the configured objects this is represented by the
4027logger holding a reference to the handler. In the configuration dict,
4028this is done by giving each destination object an id which identifies
4029it unambiguously, and then using the id in the source object's
4030configuration to indicate that a connection exists between the source
4031and the destination object with that id.
4032
4033So, for example, consider the following YAML snippet::
4034
4035 formatters:
4036 brief:
4037 # configuration for formatter with id 'brief' goes here
4038 precise:
4039 # configuration for formatter with id 'precise' goes here
4040 handlers:
4041 h1: #This is an id
4042 # configuration of handler with id 'h1' goes here
4043 formatter: brief
4044 h2: #This is another id
4045 # configuration of handler with id 'h2' goes here
4046 formatter: precise
4047 loggers:
4048 foo.bar.baz:
4049 # other configuration for logger 'foo.bar.baz'
4050 handlers: [h1, h2]
4051
4052(Note: YAML used here because it's a little more readable than the
4053equivalent Python source form for the dictionary.)
4054
4055The ids for loggers are the logger names which would be used
4056programmatically to obtain a reference to those loggers, e.g.
4057``foo.bar.baz``. The ids for Formatters and Filters can be any string
4058value (such as ``brief``, ``precise`` above) and they are transient,
4059in that they are only meaningful for processing the configuration
4060dictionary and used to determine connections between objects, and are
4061not persisted anywhere when the configuration call is complete.
4062
4063The above snippet indicates that logger named ``foo.bar.baz`` should
4064have two handlers attached to it, which are described by the handler
4065ids ``h1`` and ``h2``. The formatter for ``h1`` is that described by id
4066``brief``, and the formatter for ``h2`` is that described by id
4067``precise``.
4068
4069
4070.. _logging-config-dict-userdef:
4071
4072User-defined objects
4073""""""""""""""""""""
4074
4075The schema supports user-defined objects for handlers, filters and
4076formatters. (Loggers do not need to have different types for
4077different instances, so there is no support in this configuration
4078schema for user-defined logger classes.)
4079
4080Objects to be configured are described by dictionaries
4081which detail their configuration. In some places, the logging system
4082will be able to infer from the context how an object is to be
4083instantiated, but when a user-defined object is to be instantiated,
4084the system will not know how to do this. In order to provide complete
4085flexibility for user-defined object instantiation, the user needs
4086to provide a 'factory' - a callable which is called with a
4087configuration dictionary and which returns the instantiated object.
4088This is signalled by an absolute import path to the factory being
4089made available under the special key ``'()'``. Here's a concrete
4090example::
4091
4092 formatters:
4093 brief:
4094 format: '%(message)s'
4095 default:
4096 format: '%(asctime)s %(levelname)-8s %(name)-15s %(message)s'
4097 datefmt: '%Y-%m-%d %H:%M:%S'
4098 custom:
4099 (): my.package.customFormatterFactory
4100 bar: baz
4101 spam: 99.9
4102 answer: 42
4103
4104The above YAML snippet defines three formatters. The first, with id
4105``brief``, is a standard :class:`logging.Formatter` instance with the
4106specified format string. The second, with id ``default``, has a
4107longer format and also defines the time format explicitly, and will
4108result in a :class:`logging.Formatter` initialized with those two format
4109strings. Shown in Python source form, the ``brief`` and ``default``
4110formatters have configuration sub-dictionaries::
4111
4112 {
4113 'format' : '%(message)s'
4114 }
4115
4116and::
4117
4118 {
4119 'format' : '%(asctime)s %(levelname)-8s %(name)-15s %(message)s',
4120 'datefmt' : '%Y-%m-%d %H:%M:%S'
4121 }
4122
4123respectively, and as these dictionaries do not contain the special key
4124``'()'``, the instantiation is inferred from the context: as a result,
4125standard :class:`logging.Formatter` instances are created. The
4126configuration sub-dictionary for the third formatter, with id
4127``custom``, is::
4128
4129 {
4130 '()' : 'my.package.customFormatterFactory',
4131 'bar' : 'baz',
4132 'spam' : 99.9,
4133 'answer' : 42
4134 }
4135
4136and this contains the special key ``'()'``, which means that
4137user-defined instantiation is wanted. In this case, the specified
4138factory callable will be used. If it is an actual callable it will be
4139used directly - otherwise, if you specify a string (as in the example)
4140the actual callable will be located using normal import mechanisms.
4141The callable will be called with the **remaining** items in the
4142configuration sub-dictionary as keyword arguments. In the above
4143example, the formatter with id ``custom`` will be assumed to be
4144returned by the call::
4145
4146 my.package.customFormatterFactory(bar='baz', spam=99.9, answer=42)
4147
4148The key ``'()'`` has been used as the special key because it is not a
4149valid keyword parameter name, and so will not clash with the names of
4150the keyword arguments used in the call. The ``'()'`` also serves as a
4151mnemonic that the corresponding value is a callable.
4152
4153
4154.. _logging-config-dict-externalobj:
4155
4156Access to external objects
4157""""""""""""""""""""""""""
4158
4159There are times where a configuration needs to refer to objects
4160external to the configuration, for example ``sys.stderr``. If the
4161configuration dict is constructed using Python code, this is
4162straightforward, but a problem arises when the configuration is
4163provided via a text file (e.g. JSON, YAML). In a text file, there is
4164no standard way to distinguish ``sys.stderr`` from the literal string
4165``'sys.stderr'``. To facilitate this distinction, the configuration
4166system looks for certain special prefixes in string values and
4167treat them specially. For example, if the literal string
4168``'ext://sys.stderr'`` is provided as a value in the configuration,
4169then the ``ext://`` will be stripped off and the remainder of the
4170value processed using normal import mechanisms.
4171
4172The handling of such prefixes is done in a way analogous to protocol
4173handling: there is a generic mechanism to look for prefixes which
4174match the regular expression ``^(?P<prefix>[a-z]+)://(?P<suffix>.*)$``
4175whereby, if the ``prefix`` is recognised, the ``suffix`` is processed
4176in a prefix-dependent manner and the result of the processing replaces
4177the string value. If the prefix is not recognised, then the string
4178value will be left as-is.
4179
4180
4181.. _logging-config-dict-internalobj:
4182
4183Access to internal objects
4184""""""""""""""""""""""""""
4185
4186As well as external objects, there is sometimes also a need to refer
4187to objects in the configuration. This will be done implicitly by the
4188configuration system for things that it knows about. For example, the
4189string value ``'DEBUG'`` for a ``level`` in a logger or handler will
4190automatically be converted to the value ``logging.DEBUG``, and the
4191``handlers``, ``filters`` and ``formatter`` entries will take an
4192object id and resolve to the appropriate destination object.
4193
4194However, a more generic mechanism is needed for user-defined
4195objects which are not known to the :mod:`logging` module. For
4196example, consider :class:`logging.handlers.MemoryHandler`, which takes
4197a ``target`` argument which is another handler to delegate to. Since
4198the system already knows about this class, then in the configuration,
4199the given ``target`` just needs to be the object id of the relevant
4200target handler, and the system will resolve to the handler from the
4201id. If, however, a user defines a ``my.package.MyHandler`` which has
4202an ``alternate`` handler, the configuration system would not know that
4203the ``alternate`` referred to a handler. To cater for this, a generic
4204resolution system allows the user to specify::
4205
4206 handlers:
4207 file:
4208 # configuration of file handler goes here
4209
4210 custom:
4211 (): my.package.MyHandler
4212 alternate: cfg://handlers.file
4213
4214The literal string ``'cfg://handlers.file'`` will be resolved in an
4215analogous way to strings with the ``ext://`` prefix, but looking
4216in the configuration itself rather than the import namespace. The
4217mechanism allows access by dot or by index, in a similar way to
4218that provided by ``str.format``. Thus, given the following snippet::
4219
4220 handlers:
4221 email:
4222 class: logging.handlers.SMTPHandler
4223 mailhost: localhost
4224 fromaddr: my_app@domain.tld
4225 toaddrs:
4226 - support_team@domain.tld
4227 - dev_team@domain.tld
4228 subject: Houston, we have a problem.
4229
4230in the configuration, the string ``'cfg://handlers'`` would resolve to
4231the dict with key ``handlers``, the string ``'cfg://handlers.email``
4232would resolve to the dict with key ``email`` in the ``handlers`` dict,
4233and so on. The string ``'cfg://handlers.email.toaddrs[1]`` would
4234resolve to ``'dev_team.domain.tld'`` and the string
4235``'cfg://handlers.email.toaddrs[0]'`` would resolve to the value
4236``'support_team@domain.tld'``. The ``subject`` value could be accessed
4237using either ``'cfg://handlers.email.subject'`` or, equivalently,
4238``'cfg://handlers.email[subject]'``. The latter form only needs to be
4239used if the key contains spaces or non-alphanumeric characters. If an
4240index value consists only of decimal digits, access will be attempted
4241using the corresponding integer value, falling back to the string
4242value if needed.
4243
4244Given a string ``cfg://handlers.myhandler.mykey.123``, this will
4245resolve to ``config_dict['handlers']['myhandler']['mykey']['123']``.
4246If the string is specified as ``cfg://handlers.myhandler.mykey[123]``,
4247the system will attempt to retrieve the value from
4248``config_dict['handlers']['myhandler']['mykey'][123]``, and fall back
4249to ``config_dict['handlers']['myhandler']['mykey']['123']`` if that
4250fails.
4251
Georg Brandl116aa622007-08-15 14:28:22 +00004252.. _logging-config-fileformat:
4253
4254Configuration file format
4255^^^^^^^^^^^^^^^^^^^^^^^^^
4256
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00004257The configuration file format understood by :func:`fileConfig` is based on
4258:mod:`configparser` functionality. The file must contain sections called
4259``[loggers]``, ``[handlers]`` and ``[formatters]`` which identify by name the
4260entities of each type which are defined in the file. For each such entity, there
4261is a separate section which identifies how that entity is configured. Thus, for
4262a logger named ``log01`` in the ``[loggers]`` section, the relevant
4263configuration details are held in a section ``[logger_log01]``. Similarly, a
4264handler called ``hand01`` in the ``[handlers]`` section will have its
4265configuration held in a section called ``[handler_hand01]``, while a formatter
4266called ``form01`` in the ``[formatters]`` section will have its configuration
4267specified in a section called ``[formatter_form01]``. The root logger
4268configuration must be specified in a section called ``[logger_root]``.
Georg Brandl116aa622007-08-15 14:28:22 +00004269
4270Examples of these sections in the file are given below. ::
4271
4272 [loggers]
4273 keys=root,log02,log03,log04,log05,log06,log07
4274
4275 [handlers]
4276 keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
4277
4278 [formatters]
4279 keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
4280
4281The root logger must specify a level and a list of handlers. An example of a
4282root logger section is given below. ::
4283
4284 [logger_root]
4285 level=NOTSET
4286 handlers=hand01
4287
4288The ``level`` entry can be one of ``DEBUG, INFO, WARNING, ERROR, CRITICAL`` or
4289``NOTSET``. For the root logger only, ``NOTSET`` means that all messages will be
4290logged. Level values are :func:`eval`\ uated in the context of the ``logging``
4291package's namespace.
4292
4293The ``handlers`` entry is a comma-separated list of handler names, which must
4294appear in the ``[handlers]`` section. These names must appear in the
4295``[handlers]`` section and have corresponding sections in the configuration
4296file.
4297
4298For loggers other than the root logger, some additional information is required.
4299This is illustrated by the following example. ::
4300
4301 [logger_parser]
4302 level=DEBUG
4303 handlers=hand01
4304 propagate=1
4305 qualname=compiler.parser
4306
4307The ``level`` and ``handlers`` entries are interpreted as for the root logger,
4308except that if a non-root logger's level is specified as ``NOTSET``, the system
4309consults loggers higher up the hierarchy to determine the effective level of the
4310logger. The ``propagate`` entry is set to 1 to indicate that messages must
4311propagate to handlers higher up the logger hierarchy from this logger, or 0 to
4312indicate that messages are **not** propagated to handlers up the hierarchy. The
4313``qualname`` entry is the hierarchical channel name of the logger, that is to
4314say the name used by the application to get the logger.
4315
4316Sections which specify handler configuration are exemplified by the following.
4317::
4318
4319 [handler_hand01]
4320 class=StreamHandler
4321 level=NOTSET
4322 formatter=form01
4323 args=(sys.stdout,)
4324
4325The ``class`` entry indicates the handler's class (as determined by :func:`eval`
4326in the ``logging`` package's namespace). The ``level`` is interpreted as for
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004327loggers, and ``NOTSET`` is taken to mean 'log everything'.
Georg Brandl116aa622007-08-15 14:28:22 +00004328
4329The ``formatter`` entry indicates the key name of the formatter for this
4330handler. If blank, a default formatter (``logging._defaultFormatter``) is used.
4331If a name is specified, it must appear in the ``[formatters]`` section and have
4332a corresponding section in the configuration file.
4333
4334The ``args`` entry, when :func:`eval`\ uated in the context of the ``logging``
4335package's namespace, is the list of arguments to the constructor for the handler
4336class. Refer to the constructors for the relevant handlers, or to the examples
4337below, to see how typical entries are constructed. ::
4338
4339 [handler_hand02]
4340 class=FileHandler
4341 level=DEBUG
4342 formatter=form02
4343 args=('python.log', 'w')
4344
4345 [handler_hand03]
4346 class=handlers.SocketHandler
4347 level=INFO
4348 formatter=form03
4349 args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
4350
4351 [handler_hand04]
4352 class=handlers.DatagramHandler
4353 level=WARN
4354 formatter=form04
4355 args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
4356
4357 [handler_hand05]
4358 class=handlers.SysLogHandler
4359 level=ERROR
4360 formatter=form05
4361 args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
4362
4363 [handler_hand06]
4364 class=handlers.NTEventLogHandler
4365 level=CRITICAL
4366 formatter=form06
4367 args=('Python Application', '', 'Application')
4368
4369 [handler_hand07]
4370 class=handlers.SMTPHandler
4371 level=WARN
4372 formatter=form07
4373 args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
4374
4375 [handler_hand08]
4376 class=handlers.MemoryHandler
4377 level=NOTSET
4378 formatter=form08
4379 target=
4380 args=(10, ERROR)
4381
4382 [handler_hand09]
4383 class=handlers.HTTPHandler
4384 level=NOTSET
4385 formatter=form09
4386 args=('localhost:9022', '/log', 'GET')
4387
4388Sections which specify formatter configuration are typified by the following. ::
4389
4390 [formatter_form01]
4391 format=F1 %(asctime)s %(levelname)s %(message)s
4392 datefmt=
4393 class=logging.Formatter
4394
4395The ``format`` entry is the overall format string, and the ``datefmt`` entry is
Christian Heimes5b5e81c2007-12-31 16:14:33 +00004396the :func:`strftime`\ -compatible date/time format string. If empty, the
4397package substitutes ISO8601 format date/times, which is almost equivalent to
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004398specifying the date format string ``'%Y-%m-%d %H:%M:%S'``. The ISO8601 format
Christian Heimes5b5e81c2007-12-31 16:14:33 +00004399also specifies milliseconds, which are appended to the result of using the above
4400format string, with a comma separator. An example time in ISO8601 format is
4401``2003-01-23 00:29:50,411``.
Georg Brandl116aa622007-08-15 14:28:22 +00004402
4403The ``class`` entry is optional. It indicates the name of the formatter's class
4404(as a dotted module and class name.) This option is useful for instantiating a
4405:class:`Formatter` subclass. Subclasses of :class:`Formatter` can present
4406exception tracebacks in an expanded or condensed format.
4407
Christian Heimes8b0facf2007-12-04 19:30:01 +00004408
4409Configuration server example
4410^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4411
4412Here is an example of a module using the logging configuration server::
4413
4414 import logging
4415 import logging.config
4416 import time
4417 import os
4418
4419 # read initial config file
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004420 logging.config.fileConfig('logging.conf')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004421
4422 # create and start listener on port 9999
4423 t = logging.config.listen(9999)
4424 t.start()
4425
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004426 logger = logging.getLogger('simpleExample')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004427
4428 try:
4429 # loop through logging calls to see the difference
4430 # new configurations make, until Ctrl+C is pressed
4431 while True:
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004432 logger.debug('debug message')
4433 logger.info('info message')
4434 logger.warn('warn message')
4435 logger.error('error message')
4436 logger.critical('critical message')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004437 time.sleep(5)
4438 except KeyboardInterrupt:
4439 # cleanup
4440 logging.config.stopListening()
4441 t.join()
4442
4443And here is a script that takes a filename and sends that file to the server,
4444properly preceded with the binary-encoded length, as the new logging
4445configuration::
4446
4447 #!/usr/bin/env python
4448 import socket, sys, struct
4449
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004450 data_to_send = open(sys.argv[1], 'r').read()
Christian Heimes8b0facf2007-12-04 19:30:01 +00004451
4452 HOST = 'localhost'
4453 PORT = 9999
4454 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004455 print('connecting...')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004456 s.connect((HOST, PORT))
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004457 print('sending config...')
4458 s.send(struct.pack('>L', len(data_to_send)))
Christian Heimes8b0facf2007-12-04 19:30:01 +00004459 s.send(data_to_send)
4460 s.close()
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004461 print('complete')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004462
4463
4464More examples
4465-------------
4466
4467Multiple handlers and formatters
4468^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4469
4470Loggers are plain Python objects. The :func:`addHandler` method has no minimum
4471or maximum quota for the number of handlers you may add. Sometimes it will be
4472beneficial for an application to log all messages of all severities to a text
4473file while simultaneously logging errors or above to the console. To set this
4474up, simply configure the appropriate handlers. The logging calls in the
4475application code will remain unchanged. Here is a slight modification to the
4476previous simple module-based configuration example::
4477
4478 import logging
4479
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004480 logger = logging.getLogger('simple_example')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004481 logger.setLevel(logging.DEBUG)
4482 # create file handler which logs even debug messages
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004483 fh = logging.FileHandler('spam.log')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004484 fh.setLevel(logging.DEBUG)
4485 # create console handler with a higher log level
4486 ch = logging.StreamHandler()
4487 ch.setLevel(logging.ERROR)
4488 # create formatter and add it to the handlers
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004489 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004490 ch.setFormatter(formatter)
4491 fh.setFormatter(formatter)
4492 # add the handlers to logger
4493 logger.addHandler(ch)
4494 logger.addHandler(fh)
4495
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004496 # 'application' code
4497 logger.debug('debug message')
4498 logger.info('info message')
4499 logger.warn('warn message')
4500 logger.error('error message')
4501 logger.critical('critical message')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004502
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004503Notice that the 'application' code does not care about multiple handlers. All
Christian Heimes8b0facf2007-12-04 19:30:01 +00004504that changed was the addition and configuration of a new handler named *fh*.
4505
4506The ability to create new handlers with higher- or lower-severity filters can be
4507very helpful when writing and testing an application. Instead of using many
4508``print`` statements for debugging, use ``logger.debug``: Unlike the print
4509statements, which you will have to delete or comment out later, the logger.debug
4510statements can remain intact in the source code and remain dormant until you
4511need them again. At that time, the only change that needs to happen is to
4512modify the severity level of the logger and/or handler to debug.
4513
4514
4515Using logging in multiple modules
4516^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4517
4518It was mentioned above that multiple calls to
4519``logging.getLogger('someLogger')`` return a reference to the same logger
4520object. This is true not only within the same module, but also across modules
4521as long as it is in the same Python interpreter process. It is true for
4522references to the same object; additionally, application code can define and
4523configure a parent logger in one module and create (but not configure) a child
4524logger in a separate module, and all logger calls to the child will pass up to
4525the parent. Here is a main module::
4526
4527 import logging
4528 import auxiliary_module
4529
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004530 # create logger with 'spam_application'
4531 logger = logging.getLogger('spam_application')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004532 logger.setLevel(logging.DEBUG)
4533 # create file handler which logs even debug messages
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004534 fh = logging.FileHandler('spam.log')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004535 fh.setLevel(logging.DEBUG)
4536 # create console handler with a higher log level
4537 ch = logging.StreamHandler()
4538 ch.setLevel(logging.ERROR)
4539 # create formatter and add it to the handlers
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004540 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004541 fh.setFormatter(formatter)
4542 ch.setFormatter(formatter)
4543 # add the handlers to the logger
4544 logger.addHandler(fh)
4545 logger.addHandler(ch)
4546
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004547 logger.info('creating an instance of auxiliary_module.Auxiliary')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004548 a = auxiliary_module.Auxiliary()
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004549 logger.info('created an instance of auxiliary_module.Auxiliary')
4550 logger.info('calling auxiliary_module.Auxiliary.do_something')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004551 a.do_something()
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004552 logger.info('finished auxiliary_module.Auxiliary.do_something')
4553 logger.info('calling auxiliary_module.some_function()')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004554 auxiliary_module.some_function()
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004555 logger.info('done with auxiliary_module.some_function()')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004556
4557Here is the auxiliary module::
4558
4559 import logging
4560
4561 # create logger
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004562 module_logger = logging.getLogger('spam_application.auxiliary')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004563
4564 class Auxiliary:
4565 def __init__(self):
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004566 self.logger = logging.getLogger('spam_application.auxiliary.Auxiliary')
4567 self.logger.info('creating an instance of Auxiliary')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004568 def do_something(self):
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004569 self.logger.info('doing something')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004570 a = 1 + 1
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004571 self.logger.info('done doing something')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004572
4573 def some_function():
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004574 module_logger.info('received a call to "some_function"')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004575
4576The output looks like this::
4577
Christian Heimes043d6f62008-01-07 17:19:16 +00004578 2005-03-23 23:47:11,663 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004579 creating an instance of auxiliary_module.Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00004580 2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004581 creating an instance of Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00004582 2005-03-23 23:47:11,665 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004583 created an instance of auxiliary_module.Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00004584 2005-03-23 23:47:11,668 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004585 calling auxiliary_module.Auxiliary.do_something
Christian Heimes043d6f62008-01-07 17:19:16 +00004586 2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004587 doing something
Christian Heimes043d6f62008-01-07 17:19:16 +00004588 2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004589 done doing something
Christian Heimes043d6f62008-01-07 17:19:16 +00004590 2005-03-23 23:47:11,670 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004591 finished auxiliary_module.Auxiliary.do_something
Christian Heimes043d6f62008-01-07 17:19:16 +00004592 2005-03-23 23:47:11,671 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004593 calling auxiliary_module.some_function()
Christian Heimes043d6f62008-01-07 17:19:16 +00004594 2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004595 received a call to 'some_function'
Christian Heimes043d6f62008-01-07 17:19:16 +00004596 2005-03-23 23:47:11,673 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004597 done with auxiliary_module.some_function()
4598