blob: b71a37f8b5181ef7b2af11ec09422146e4369201 [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
567The following example configures a very simple logger, a console
568handler, and a simple formatter using Python code::
Christian Heimes8b0facf2007-12-04 19:30:01 +0000569
570 import logging
571
572 # create logger
Vinay Sajip9a6b4002010-12-14 19:40:21 +0000573 logger = logging.getLogger('simple_example')
Christian Heimes8b0facf2007-12-04 19:30:01 +0000574 logger.setLevel(logging.DEBUG)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000575
Christian Heimes8b0facf2007-12-04 19:30:01 +0000576 # create console handler and set level to debug
577 ch = logging.StreamHandler()
578 ch.setLevel(logging.DEBUG)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000579
Christian Heimes8b0facf2007-12-04 19:30:01 +0000580 # create formatter
Vinay Sajip9a6b4002010-12-14 19:40:21 +0000581 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000582
Christian Heimes8b0facf2007-12-04 19:30:01 +0000583 # add formatter to ch
584 ch.setFormatter(formatter)
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000585
Christian Heimes8b0facf2007-12-04 19:30:01 +0000586 # add ch to logger
587 logger.addHandler(ch)
588
Vinay Sajip9a6b4002010-12-14 19:40:21 +0000589 # 'application' code
590 logger.debug('debug message')
591 logger.info('info message')
592 logger.warn('warn message')
593 logger.error('error message')
594 logger.critical('critical message')
Christian Heimes8b0facf2007-12-04 19:30:01 +0000595
596Running this module from the command line produces the following output::
597
598 $ python simple_logging_module.py
599 2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
600 2005-03-19 15:10:26,620 - simple_example - INFO - info message
601 2005-03-19 15:10:26,695 - simple_example - WARNING - warn message
602 2005-03-19 15:10:26,697 - simple_example - ERROR - error message
603 2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message
604
605The following Python module creates a logger, handler, and formatter nearly
606identical to those in the example listed above, with the only difference being
607the names of the objects::
608
609 import logging
610 import logging.config
611
Vinay Sajip9a6b4002010-12-14 19:40:21 +0000612 logging.config.fileConfig('logging.conf')
Christian Heimes8b0facf2007-12-04 19:30:01 +0000613
614 # create logger
Vinay Sajip9a6b4002010-12-14 19:40:21 +0000615 logger = logging.getLogger('simpleExample')
Christian Heimes8b0facf2007-12-04 19:30:01 +0000616
Vinay Sajip9a6b4002010-12-14 19:40:21 +0000617 # 'application' code
618 logger.debug('debug message')
619 logger.info('info message')
620 logger.warn('warn message')
621 logger.error('error message')
622 logger.critical('critical message')
Christian Heimes8b0facf2007-12-04 19:30:01 +0000623
624Here is the logging.conf file::
625
626 [loggers]
627 keys=root,simpleExample
628
629 [handlers]
630 keys=consoleHandler
631
632 [formatters]
633 keys=simpleFormatter
634
635 [logger_root]
636 level=DEBUG
637 handlers=consoleHandler
638
639 [logger_simpleExample]
640 level=DEBUG
641 handlers=consoleHandler
642 qualname=simpleExample
643 propagate=0
644
645 [handler_consoleHandler]
646 class=StreamHandler
647 level=DEBUG
648 formatter=simpleFormatter
649 args=(sys.stdout,)
650
651 [formatter_simpleFormatter]
652 format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
653 datefmt=
654
655The output is nearly identical to that of the non-config-file-based example::
656
657 $ python simple_logging_config.py
658 2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
659 2005-03-19 15:38:55,979 - simpleExample - INFO - info message
660 2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
661 2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
662 2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message
663
664You can see that the config file approach has a few advantages over the Python
665code approach, mainly separation of configuration and code and the ability of
666noncoders to easily modify the logging properties.
667
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000668Note that the class names referenced in config files need to be either relative
669to the logging module, or absolute values which can be resolved using normal
Senthil Kumaran46a48be2010-10-15 13:10:10 +0000670import mechanisms. Thus, you could use either
671:class:`handlers.WatchedFileHandler` (relative to the logging module) or
672``mypackage.mymodule.MyHandler`` (for a class defined in package ``mypackage``
673and module ``mymodule``, where ``mypackage`` is available on the Python import
674path).
Benjamin Peterson9451a1c2010-03-13 22:30:34 +0000675
Benjamin Peterson56894b52010-06-28 00:16:12 +0000676In Python 3.2, a new means of configuring logging has been introduced, using
Benjamin Petersond7c3ed52010-06-27 22:32:30 +0000677dictionaries to hold configuration information. This provides a superset of the
678functionality of the config-file-based approach outlined above, and is the
679recommended configuration method for new applications and deployments. Because
680a Python dictionary is used to hold configuration information, and since you
681can populate that dictionary using different means, you have more options for
682configuration. For example, you can use a configuration file in JSON format,
683or, if you have access to YAML processing functionality, a file in YAML
684format, to populate the configuration dictionary. Or, of course, you can
685construct the dictionary in Python code, receive it in pickled form over a
686socket, or use whatever approach makes sense for your application.
687
688Here's an example of the same configuration as above, in YAML format for
689the new dictionary-based approach::
690
691 version: 1
692 formatters:
693 simple:
694 format: format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
695 handlers:
696 console:
697 class: logging.StreamHandler
698 level: DEBUG
699 formatter: simple
700 stream: ext://sys.stdout
701 loggers:
702 simpleExample:
703 level: DEBUG
704 handlers: [console]
705 propagate: no
706 root:
707 level: DEBUG
708 handlers: [console]
709
710For more information about logging using a dictionary, see
711:ref:`logging-config-api`.
712
Vinay Sajipf234eb92010-12-12 17:37:27 +0000713What happens if no configuration is provided
714^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
715
716If no logging configuration is provided, it is possible to have a situation
717where a logging event needs to be output, but no handlers can be found to
718output the event. The behaviour of the logging package in these
719circumstances is dependent on the Python version.
720
721For versions of Python prior to 3.2, the behaviour is as follows:
722
723* If *logging.raiseExceptions* is *False* (production mode), the event is
724 silently dropped.
725
726* If *logging.raiseExceptions* is *True* (development mode), a message
Vinay Sajip9a6b4002010-12-14 19:40:21 +0000727 'No handlers could be found for logger X.Y.Z' is printed once.
Vinay Sajipf234eb92010-12-12 17:37:27 +0000728
729In Python 3.2 and later, the behaviour is as follows:
730
Vinay Sajip9a6b4002010-12-14 19:40:21 +0000731* The event is output using a 'handler of last resort', stored in
Vinay Sajipf234eb92010-12-12 17:37:27 +0000732 ``logging.lastResort``. This internal handler is not associated with any
733 logger, and acts like a :class:`StreamHandler` which writes the event
734 description message to the current value of ``sys.stderr`` (therefore
735 respecting any redirections which may be in effect). No formatting is
736 done on the message - just the bare event description message is printed.
737 The handler's level is set to ``WARNING``, so all events at this and
738 greater severities will be output.
739
740To obtain the pre-3.2 behaviour, ``logging.lastResort`` can be set to *None*.
741
Vinay Sajip26a2d5e2009-01-10 13:37:26 +0000742.. _library-config:
Vinay Sajip30bf1222009-01-10 19:23:34 +0000743
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000744Configuring Logging for a Library
745^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
746
Vinay Sajipf234eb92010-12-12 17:37:27 +0000747When developing a library which uses logging, you should take care to
748document how the library uses logging - for example, the names of loggers
749used. Some consideration also needs to be given to its logging configuration.
750If the using application does not use logging, and library code makes logging
751calls, then (as described in the previous section) events of severity
752``WARNING`` and greater will be printed to ``sys.stderr``. This is regarded as
753the best default behaviour.
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000754
Vinay Sajipf234eb92010-12-12 17:37:27 +0000755If for some reason you *don't* want these messages printed in the absence of
756any logging configuration, you can attach a do-nothing handler to the top-level
757logger for your library. This avoids the message being printed, since a handler
758will be always be found for the library's events: it just doesn't produce any
759output. If the library user configures logging for application use, presumably
760that configuration will add some handlers, and if levels are suitably
761configured then logging calls made in library code will send output to those
762handlers, as normal.
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000763
Vinay Sajipf234eb92010-12-12 17:37:27 +0000764A do-nothing handler is included in the logging package: :class:`NullHandler`
765(since Python 3.1). An instance of this handler could be added to the top-level
766logger of the logging namespace used by the library (*if* you want to prevent
767your library's logged events being output to ``sys.stderr`` in the absence of
768logging configuration). If all logging by a library *foo* is done using loggers
769with names matching 'foo.x', 'foo.x.y', etc. then the code::
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000770
771 import logging
Vinay Sajipf234eb92010-12-12 17:37:27 +0000772 logging.getLogger('foo').addHandler(logging.NullHandler())
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000773
774should have the desired effect. If an organisation produces a number of
Vinay Sajipf234eb92010-12-12 17:37:27 +0000775libraries, then the logger name specified can be 'orgname.foo' rather than
776just 'foo'.
Benjamin Peterson3e4f0552008-09-02 00:31:15 +0000777
Vinay Sajip76ca3b42010-09-27 13:53:47 +0000778**PLEASE NOTE:** It is strongly advised that you *do not add any handlers other
779than* :class:`NullHandler` *to your library's loggers*. This is because the
780configuration of handlers is the prerogative of the application developer who
781uses your library. The application developer knows their target audience and
782what handlers are most appropriate for their application: if you add handlers
Vinay Sajip9a6b4002010-12-14 19:40:21 +0000783'under the hood', you might well interfere with their ability to carry out
Vinay Sajip76ca3b42010-09-27 13:53:47 +0000784unit tests and deliver logs which suit their requirements.
785
Christian Heimes8b0facf2007-12-04 19:30:01 +0000786
787Logging Levels
788--------------
789
Georg Brandl116aa622007-08-15 14:28:22 +0000790The numeric values of logging levels are given in the following table. These are
791primarily of interest if you want to define your own levels, and need them to
792have specific values relative to the predefined levels. If you define a level
793with the same numeric value, it overwrites the predefined value; the predefined
794name is lost.
795
796+--------------+---------------+
797| Level | Numeric value |
798+==============+===============+
799| ``CRITICAL`` | 50 |
800+--------------+---------------+
801| ``ERROR`` | 40 |
802+--------------+---------------+
803| ``WARNING`` | 30 |
804+--------------+---------------+
805| ``INFO`` | 20 |
806+--------------+---------------+
807| ``DEBUG`` | 10 |
808+--------------+---------------+
809| ``NOTSET`` | 0 |
810+--------------+---------------+
811
812Levels can also be associated with loggers, being set either by the developer or
813through loading a saved logging configuration. When a logging method is called
814on a logger, the logger compares its own level with the level associated with
815the method call. If the logger's level is higher than the method call's, no
816logging message is actually generated. This is the basic mechanism controlling
817the verbosity of logging output.
818
819Logging messages are encoded as instances of the :class:`LogRecord` class. When
820a logger decides to actually log an event, a :class:`LogRecord` instance is
821created from the logging message.
822
823Logging messages are subjected to a dispatch mechanism through the use of
824:dfn:`handlers`, which are instances of subclasses of the :class:`Handler`
825class. Handlers are responsible for ensuring that a logged message (in the form
826of a :class:`LogRecord`) ends up in a particular location (or set of locations)
827which is useful for the target audience for that message (such as end users,
828support desk staff, system administrators, developers). Handlers are passed
829:class:`LogRecord` instances intended for particular destinations. Each logger
830can have zero, one or more handlers associated with it (via the
831:meth:`addHandler` method of :class:`Logger`). In addition to any handlers
832directly associated with a logger, *all handlers associated with all ancestors
Benjamin Peterson22005fc2010-04-11 16:25:06 +0000833of the logger* are called to dispatch the message (unless the *propagate* flag
834for a logger is set to a false value, at which point the passing to ancestor
835handlers stops).
Georg Brandl116aa622007-08-15 14:28:22 +0000836
837Just as for loggers, handlers can have levels associated with them. A handler's
838level acts as a filter in the same way as a logger's level does. If a handler
839decides to actually dispatch an event, the :meth:`emit` method is used to send
840the message to its destination. Most user-defined subclasses of :class:`Handler`
841will need to override this :meth:`emit`.
842
Vinay Sajipc8c8c692010-09-17 10:09:04 +0000843.. _custom-levels:
844
845Custom Levels
846^^^^^^^^^^^^^
847
848Defining your own levels is possible, but should not be necessary, as the
849existing levels have been chosen on the basis of practical experience.
850However, if you are convinced that you need custom levels, great care should
851be exercised when doing this, and it is possibly *a very bad idea to define
852custom levels if you are developing a library*. That's because if multiple
853library authors all define their own custom levels, there is a chance that
854the logging output from such multiple libraries used together will be
855difficult for the using developer to control and/or interpret, because a
856given numeric value might mean different things for different libraries.
857
858
Vinay Sajipf234eb92010-12-12 17:37:27 +0000859.. _useful-handlers:
860
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000861Useful Handlers
862---------------
863
Georg Brandl116aa622007-08-15 14:28:22 +0000864In addition to the base :class:`Handler` class, many useful subclasses are
865provided:
866
Vinay Sajip121a1c42010-09-08 10:46:15 +0000867#. :class:`StreamHandler` instances send messages to streams (file-like
Georg Brandl116aa622007-08-15 14:28:22 +0000868 objects).
869
Vinay Sajip121a1c42010-09-08 10:46:15 +0000870#. :class:`FileHandler` instances send messages to disk files.
Georg Brandl116aa622007-08-15 14:28:22 +0000871
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000872.. module:: logging.handlers
Vinay Sajip30bf1222009-01-10 19:23:34 +0000873
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000874#. :class:`BaseRotatingHandler` is the base class for handlers that
875 rotate log files at a certain point. It is not meant to be instantiated
876 directly. Instead, use :class:`RotatingFileHandler` or
877 :class:`TimedRotatingFileHandler`.
Georg Brandl116aa622007-08-15 14:28:22 +0000878
Vinay Sajip121a1c42010-09-08 10:46:15 +0000879#. :class:`RotatingFileHandler` instances send messages to disk
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000880 files, with support for maximum log file sizes and log file rotation.
Georg Brandl116aa622007-08-15 14:28:22 +0000881
Vinay Sajip121a1c42010-09-08 10:46:15 +0000882#. :class:`TimedRotatingFileHandler` instances send messages to
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000883 disk files, rotating the log file at certain timed intervals.
Georg Brandl116aa622007-08-15 14:28:22 +0000884
Vinay Sajip121a1c42010-09-08 10:46:15 +0000885#. :class:`SocketHandler` instances send messages to TCP/IP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000886 sockets.
Georg Brandl116aa622007-08-15 14:28:22 +0000887
Vinay Sajip121a1c42010-09-08 10:46:15 +0000888#. :class:`DatagramHandler` instances send messages to UDP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000889 sockets.
Georg Brandl116aa622007-08-15 14:28:22 +0000890
Vinay Sajip121a1c42010-09-08 10:46:15 +0000891#. :class:`SMTPHandler` instances send messages to a designated
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000892 email address.
Georg Brandl116aa622007-08-15 14:28:22 +0000893
Vinay Sajip121a1c42010-09-08 10:46:15 +0000894#. :class:`SysLogHandler` instances send messages to a Unix
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000895 syslog daemon, possibly on a remote machine.
Georg Brandl116aa622007-08-15 14:28:22 +0000896
Vinay Sajip121a1c42010-09-08 10:46:15 +0000897#. :class:`NTEventLogHandler` instances send messages to a
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000898 Windows NT/2000/XP event log.
Georg Brandl116aa622007-08-15 14:28:22 +0000899
Vinay Sajip121a1c42010-09-08 10:46:15 +0000900#. :class:`MemoryHandler` instances send messages to a buffer
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000901 in memory, which is flushed whenever specific criteria are met.
Georg Brandl116aa622007-08-15 14:28:22 +0000902
Vinay Sajip121a1c42010-09-08 10:46:15 +0000903#. :class:`HTTPHandler` instances send messages to an HTTP
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000904 server using either ``GET`` or ``POST`` semantics.
Georg Brandl116aa622007-08-15 14:28:22 +0000905
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000906#. :class:`WatchedFileHandler` instances watch the file they are
907 logging to. If the file changes, it is closed and reopened using the file
908 name. This handler is only useful on Unix-like systems; Windows does not
909 support the underlying mechanism used.
Vinay Sajip30bf1222009-01-10 19:23:34 +0000910
Vinay Sajip121a1c42010-09-08 10:46:15 +0000911#. :class:`QueueHandler` instances send messages to a queue, such as
912 those implemented in the :mod:`queue` or :mod:`multiprocessing` modules.
913
Vinay Sajip30bf1222009-01-10 19:23:34 +0000914.. currentmodule:: logging
915
Georg Brandlf9734072008-12-07 15:30:06 +0000916#. :class:`NullHandler` instances do nothing with error messages. They are used
Vinay Sajip9a6b4002010-12-14 19:40:21 +0000917 by library developers who want to use logging, but want to avoid the 'No
918 handlers could be found for logger XXX' message which can be displayed if
Vinay Sajip26a2d5e2009-01-10 13:37:26 +0000919 the library user has not configured logging. See :ref:`library-config` for
920 more information.
Georg Brandlf9734072008-12-07 15:30:06 +0000921
922.. versionadded:: 3.1
Georg Brandl1eb40bc2010-12-03 15:30:09 +0000923 The :class:`NullHandler` class.
Georg Brandlf9734072008-12-07 15:30:06 +0000924
Vinay Sajip121a1c42010-09-08 10:46:15 +0000925.. versionadded:: 3.2
Vinay Sajipa18b9592010-12-12 13:20:55 +0000926 The :class:`~logging.handlers.QueueHandler` class.
Vinay Sajip121a1c42010-09-08 10:46:15 +0000927
Vinay Sajipa17775f2008-12-30 07:32:59 +0000928The :class:`NullHandler`, :class:`StreamHandler` and :class:`FileHandler`
929classes are defined in the core logging package. The other handlers are
930defined in a sub- module, :mod:`logging.handlers`. (There is also another
931sub-module, :mod:`logging.config`, for configuration functionality.)
Georg Brandl116aa622007-08-15 14:28:22 +0000932
933Logged messages are formatted for presentation through instances of the
934:class:`Formatter` class. They are initialized with a format string suitable for
935use with the % operator and a dictionary.
936
937For formatting multiple messages in a batch, instances of
938:class:`BufferingFormatter` can be used. In addition to the format string (which
939is applied to each message in the batch), there is provision for header and
940trailer format strings.
941
942When filtering based on logger level and/or handler level is not enough,
943instances of :class:`Filter` can be added to both :class:`Logger` and
944:class:`Handler` instances (through their :meth:`addFilter` method). Before
945deciding to process a message further, both loggers and handlers consult all
946their filters for permission. If any filter returns a false value, the message
947is not processed further.
948
949The basic :class:`Filter` functionality allows filtering by specific logger
950name. If this feature is used, messages sent to the named logger and its
951children are allowed through the filter, and all others dropped.
952
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000953Module-Level Functions
954----------------------
955
Georg Brandl116aa622007-08-15 14:28:22 +0000956In addition to the classes described above, there are a number of module- level
957functions.
958
959
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000960.. function:: getLogger(name=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000961
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000962 Return a logger with the specified name or, if name is ``None``, return a
Georg Brandl116aa622007-08-15 14:28:22 +0000963 logger which is the root logger of the hierarchy. If specified, the name is
Vinay Sajip9a6b4002010-12-14 19:40:21 +0000964 typically a dot-separated hierarchical name like *'a'*, *'a.b'* or *'a.b.c.d'*.
Georg Brandl116aa622007-08-15 14:28:22 +0000965 Choice of these names is entirely up to the developer who is using logging.
966
967 All calls to this function with a given name return the same logger instance.
968 This means that logger instances never need to be passed between different parts
969 of an application.
970
971
972.. function:: getLoggerClass()
973
974 Return either the standard :class:`Logger` class, or the last class passed to
975 :func:`setLoggerClass`. This function may be called from within a new class
976 definition, to ensure that installing a customised :class:`Logger` class will
977 not undo customisations already applied by other code. For example::
978
979 class MyLogger(logging.getLoggerClass()):
980 # ... override behaviour here
981
982
Vinay Sajip61561522010-12-03 11:50:38 +0000983.. function:: getLogRecordFactory()
984
985 Return a callable which is used to create a :class:`LogRecord`.
986
987 .. versionadded:: 3.2
Vinay Sajip61561522010-12-03 11:50:38 +0000988 This function has been provided, along with :func:`setLogRecordFactory`,
989 to allow developers more control over how the :class:`LogRecord`
990 representing a logging event is constructed.
991
992 See :func:`setLogRecordFactory` for more information about the how the
993 factory is called.
994
Georg Brandlcd7f32b2009-06-08 09:13:45 +0000995.. function:: debug(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +0000996
997 Logs a message with level :const:`DEBUG` on the root logger. The *msg* is the
998 message format string, and the *args* are the arguments which are merged into
999 *msg* using the string formatting operator. (Note that this means that you can
1000 use keywords in the format string, together with a single dictionary argument.)
1001
Vinay Sajip8593ae62010-11-14 21:33:04 +00001002 There are three keyword arguments in *kwargs* which are inspected: *exc_info*
Georg Brandl116aa622007-08-15 14:28:22 +00001003 which, if it does not evaluate as false, causes exception information to be
1004 added to the logging message. If an exception tuple (in the format returned by
1005 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
1006 is called to get the exception information.
1007
Vinay Sajip8593ae62010-11-14 21:33:04 +00001008 The second optional keyword argument is *stack_info*, which defaults to
1009 False. If specified as True, stack information is added to the logging
1010 message, including the actual logging call. Note that this is not the same
1011 stack information as that displayed through specifying *exc_info*: The
1012 former is stack frames from the bottom of the stack up to the logging call
1013 in the current thread, whereas the latter is information about stack frames
1014 which have been unwound, following an exception, while searching for
1015 exception handlers.
1016
1017 You can specify *stack_info* independently of *exc_info*, e.g. to just show
1018 how you got to a certain point in your code, even when no exceptions were
1019 raised. The stack frames are printed following a header line which says::
1020
1021 Stack (most recent call last):
1022
1023 This mimics the `Traceback (most recent call last):` which is used when
1024 displaying exception frames.
1025
1026 The third optional keyword argument is *extra* which can be used to pass a
Georg Brandl116aa622007-08-15 14:28:22 +00001027 dictionary which is used to populate the __dict__ of the LogRecord created for
1028 the logging event with user-defined attributes. These custom attributes can then
1029 be used as you like. For example, they could be incorporated into logged
1030 messages. For example::
1031
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001032 FORMAT = '%(asctime)-15s %(clientip)s %(user)-8s %(message)s'
Georg Brandl116aa622007-08-15 14:28:22 +00001033 logging.basicConfig(format=FORMAT)
1034 d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001035 logging.warning('Protocol problem: %s', 'connection reset', extra=d)
Georg Brandl116aa622007-08-15 14:28:22 +00001036
Vinay Sajip4039aff2010-09-11 10:25:28 +00001037 would print something like::
Georg Brandl116aa622007-08-15 14:28:22 +00001038
1039 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
1040
1041 The keys in the dictionary passed in *extra* should not clash with the keys used
1042 by the logging system. (See the :class:`Formatter` documentation for more
1043 information on which keys are used by the logging system.)
1044
1045 If you choose to use these attributes in logged messages, you need to exercise
1046 some care. In the above example, for instance, the :class:`Formatter` has been
1047 set up with a format string which expects 'clientip' and 'user' in the attribute
1048 dictionary of the LogRecord. If these are missing, the message will not be
1049 logged because a string formatting exception will occur. So in this case, you
1050 always need to pass the *extra* dictionary with these keys.
1051
1052 While this might be annoying, this feature is intended for use in specialized
1053 circumstances, such as multi-threaded servers where the same code executes in
1054 many contexts, and interesting conditions which arise are dependent on this
1055 context (such as remote client IP address and authenticated user name, in the
1056 above example). In such circumstances, it is likely that specialized
1057 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
1058
Vinay Sajip8593ae62010-11-14 21:33:04 +00001059 .. versionadded:: 3.2
1060 The *stack_info* parameter was added.
Georg Brandl116aa622007-08-15 14:28:22 +00001061
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001062.. function:: info(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001063
1064 Logs a message with level :const:`INFO` on the root logger. The arguments are
1065 interpreted as for :func:`debug`.
1066
1067
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001068.. function:: warning(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001069
1070 Logs a message with level :const:`WARNING` on the root logger. The arguments are
1071 interpreted as for :func:`debug`.
1072
1073
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001074.. function:: error(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001075
1076 Logs a message with level :const:`ERROR` on the root logger. The arguments are
1077 interpreted as for :func:`debug`.
1078
1079
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001080.. function:: critical(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001081
1082 Logs a message with level :const:`CRITICAL` on the root logger. The arguments
1083 are interpreted as for :func:`debug`.
1084
1085
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001086.. function:: exception(msg, *args)
Georg Brandl116aa622007-08-15 14:28:22 +00001087
1088 Logs a message with level :const:`ERROR` on the root logger. The arguments are
1089 interpreted as for :func:`debug`. Exception info is added to the logging
1090 message. This function should only be called from an exception handler.
1091
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001092.. function:: log(level, msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001093
1094 Logs a message with level *level* on the root logger. The other arguments are
1095 interpreted as for :func:`debug`.
1096
Vinay Sajipc8c8c692010-09-17 10:09:04 +00001097 PLEASE NOTE: The above module-level functions which delegate to the root
1098 logger should *not* be used in threads, in versions of Python earlier than
1099 2.7.1 and 3.2, unless at least one handler has been added to the root
1100 logger *before* the threads are started. These convenience functions call
1101 :func:`basicConfig` to ensure that at least one handler is available; in
1102 earlier versions of Python, this can (under rare circumstances) lead to
1103 handlers being added multiple times to the root logger, which can in turn
1104 lead to multiple messages for the same event.
Georg Brandl116aa622007-08-15 14:28:22 +00001105
1106.. function:: disable(lvl)
1107
1108 Provides an overriding level *lvl* for all loggers which takes precedence over
1109 the logger's own level. When the need arises to temporarily throttle logging
Benjamin Peterson886af962010-03-21 23:13:07 +00001110 output down across the whole application, this function can be useful. Its
1111 effect is to disable all logging calls of severity *lvl* and below, so that
1112 if you call it with a value of INFO, then all INFO and DEBUG events would be
1113 discarded, whereas those of severity WARNING and above would be processed
1114 according to the logger's effective level.
Georg Brandl116aa622007-08-15 14:28:22 +00001115
1116
1117.. function:: addLevelName(lvl, levelName)
1118
1119 Associates level *lvl* with text *levelName* in an internal dictionary, which is
1120 used to map numeric levels to a textual representation, for example when a
1121 :class:`Formatter` formats a message. This function can also be used to define
1122 your own levels. The only constraints are that all levels used must be
1123 registered using this function, levels should be positive integers and they
1124 should increase in increasing order of severity.
1125
Vinay Sajipc8c8c692010-09-17 10:09:04 +00001126 NOTE: If you are thinking of defining your own levels, please see the section
1127 on :ref:`custom-levels`.
Georg Brandl116aa622007-08-15 14:28:22 +00001128
1129.. function:: getLevelName(lvl)
1130
1131 Returns the textual representation of logging level *lvl*. If the level is one
1132 of the predefined levels :const:`CRITICAL`, :const:`ERROR`, :const:`WARNING`,
1133 :const:`INFO` or :const:`DEBUG` then you get the corresponding string. If you
1134 have associated levels with names using :func:`addLevelName` then the name you
1135 have associated with *lvl* is returned. If a numeric value corresponding to one
1136 of the defined levels is passed in, the corresponding string representation is
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001137 returned. Otherwise, the string 'Level %s' % lvl is returned.
Georg Brandl116aa622007-08-15 14:28:22 +00001138
1139
1140.. function:: makeLogRecord(attrdict)
1141
1142 Creates and returns a new :class:`LogRecord` instance whose attributes are
1143 defined by *attrdict*. This function is useful for taking a pickled
1144 :class:`LogRecord` attribute dictionary, sent over a socket, and reconstituting
1145 it as a :class:`LogRecord` instance at the receiving end.
1146
1147
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001148.. function:: basicConfig(**kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001149
1150 Does basic configuration for the logging system by creating a
1151 :class:`StreamHandler` with a default :class:`Formatter` and adding it to the
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00001152 root logger. The functions :func:`debug`, :func:`info`, :func:`warning`,
Georg Brandl116aa622007-08-15 14:28:22 +00001153 :func:`error` and :func:`critical` will call :func:`basicConfig` automatically
1154 if no handlers are defined for the root logger.
1155
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00001156 This function does nothing if the root logger already has handlers
1157 configured for it.
1158
Vinay Sajipc8c8c692010-09-17 10:09:04 +00001159 PLEASE NOTE: This function should be called from the main thread
1160 before other threads are started. In versions of Python prior to
1161 2.7.1 and 3.2, if this function is called from multiple threads,
1162 it is possible (in rare circumstances) that a handler will be added
1163 to the root logger more than once, leading to unexpected results
1164 such as messages being duplicated in the log.
1165
Georg Brandl116aa622007-08-15 14:28:22 +00001166 The following keyword arguments are supported.
1167
1168 +--------------+---------------------------------------------+
1169 | Format | Description |
1170 +==============+=============================================+
1171 | ``filename`` | Specifies that a FileHandler be created, |
1172 | | using the specified filename, rather than a |
1173 | | StreamHandler. |
1174 +--------------+---------------------------------------------+
1175 | ``filemode`` | Specifies the mode to open the file, if |
1176 | | filename is specified (if filemode is |
1177 | | unspecified, it defaults to 'a'). |
1178 +--------------+---------------------------------------------+
1179 | ``format`` | Use the specified format string for the |
1180 | | handler. |
1181 +--------------+---------------------------------------------+
1182 | ``datefmt`` | Use the specified date/time format. |
1183 +--------------+---------------------------------------------+
Vinay Sajipc5b27302010-10-31 14:59:16 +00001184 | ``style`` | If ``format`` is specified, use this style |
1185 | | for the format string. One of '%', '{' or |
1186 | | '$' for %-formatting, :meth:`str.format` or |
1187 | | :class:`string.Template` respectively, and |
1188 | | defaulting to '%' if not specified. |
1189 +--------------+---------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00001190 | ``level`` | Set the root logger level to the specified |
1191 | | level. |
1192 +--------------+---------------------------------------------+
1193 | ``stream`` | Use the specified stream to initialize the |
1194 | | StreamHandler. Note that this argument is |
1195 | | incompatible with 'filename' - if both are |
1196 | | present, 'stream' is ignored. |
1197 +--------------+---------------------------------------------+
1198
Vinay Sajipc5b27302010-10-31 14:59:16 +00001199 .. versionchanged:: 3.2
1200 The ``style`` argument was added.
1201
1202
Georg Brandl116aa622007-08-15 14:28:22 +00001203.. function:: shutdown()
1204
1205 Informs the logging system to perform an orderly shutdown by flushing and
Christian Heimesb186d002008-03-18 15:15:01 +00001206 closing all handlers. This should be called at application exit and no
1207 further use of the logging system should be made after this call.
Georg Brandl116aa622007-08-15 14:28:22 +00001208
1209
1210.. function:: setLoggerClass(klass)
1211
1212 Tells the logging system to use the class *klass* when instantiating a logger.
1213 The class should define :meth:`__init__` such that only a name argument is
1214 required, and the :meth:`__init__` should call :meth:`Logger.__init__`. This
1215 function is typically called before any loggers are instantiated by applications
1216 which need to use custom logger behavior.
1217
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001218
Vinay Sajip61561522010-12-03 11:50:38 +00001219.. function:: setLogRecordFactory(factory)
1220
1221 Set a callable which is used to create a :class:`LogRecord`.
1222
1223 :param factory: The factory callable to be used to instantiate a log record.
1224
1225 .. versionadded:: 3.2
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001226 This function has been provided, along with :func:`getLogRecordFactory`, to
1227 allow developers more control over how the :class:`LogRecord` representing
1228 a logging event is constructed.
Vinay Sajip61561522010-12-03 11:50:38 +00001229
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001230 The factory has the following signature:
Vinay Sajip61561522010-12-03 11:50:38 +00001231
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001232 ``factory(name, level, fn, lno, msg, args, exc_info, func=None, sinfo=None, **kwargs)``
Vinay Sajip61561522010-12-03 11:50:38 +00001233
1234 :name: The logger name.
1235 :level: The logging level (numeric).
1236 :fn: The full pathname of the file where the logging call was made.
1237 :lno: The line number in the file where the logging call was made.
1238 :msg: The logging message.
1239 :args: The arguments for the logging message.
1240 :exc_info: An exception tuple, or None.
1241 :func: The name of the function or method which invoked the logging
1242 call.
1243 :sinfo: A stack traceback such as is provided by
1244 :func:`traceback.print_stack`, showing the call hierarchy.
1245 :kwargs: Additional keyword arguments.
Georg Brandl116aa622007-08-15 14:28:22 +00001246
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001247
Georg Brandl116aa622007-08-15 14:28:22 +00001248.. seealso::
1249
1250 :pep:`282` - A Logging System
1251 The proposal which described this feature for inclusion in the Python standard
1252 library.
1253
Christian Heimes255f53b2007-12-08 15:33:56 +00001254 `Original Python logging package <http://www.red-dove.com/python_logging.html>`_
Georg Brandl116aa622007-08-15 14:28:22 +00001255 This is the original source for the :mod:`logging` package. The version of the
1256 package available from this site is suitable for use with Python 1.5.2, 2.1.x
1257 and 2.2.x, which do not include the :mod:`logging` package in the standard
1258 library.
1259
Vinay Sajip4039aff2010-09-11 10:25:28 +00001260.. _logger:
Georg Brandl116aa622007-08-15 14:28:22 +00001261
1262Logger Objects
1263--------------
1264
1265Loggers have the following attributes and methods. Note that Loggers are never
1266instantiated directly, but always through the module-level function
1267``logging.getLogger(name)``.
1268
Vinay Sajip0258ce82010-09-22 20:34:53 +00001269.. class:: Logger
Georg Brandl116aa622007-08-15 14:28:22 +00001270
1271.. attribute:: Logger.propagate
1272
1273 If this evaluates to false, logging messages are not passed by this logger or by
Benjamin Peterson22005fc2010-04-11 16:25:06 +00001274 its child loggers to the handlers of higher level (ancestor) loggers. The
1275 constructor sets this attribute to 1.
Georg Brandl116aa622007-08-15 14:28:22 +00001276
1277
1278.. method:: Logger.setLevel(lvl)
1279
1280 Sets the threshold for this logger to *lvl*. Logging messages which are less
1281 severe than *lvl* will be ignored. When a logger is created, the level is set to
1282 :const:`NOTSET` (which causes all messages to be processed when the logger is
1283 the root logger, or delegation to the parent when the logger is a non-root
1284 logger). Note that the root logger is created with level :const:`WARNING`.
1285
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001286 The term 'delegation to the parent' means that if a logger has a level of
Georg Brandl116aa622007-08-15 14:28:22 +00001287 NOTSET, its chain of ancestor loggers is traversed until either an ancestor with
1288 a level other than NOTSET is found, or the root is reached.
1289
1290 If an ancestor is found with a level other than NOTSET, then that ancestor's
1291 level is treated as the effective level of the logger where the ancestor search
1292 began, and is used to determine how a logging event is handled.
1293
1294 If the root is reached, and it has a level of NOTSET, then all messages will be
1295 processed. Otherwise, the root's level will be used as the effective level.
1296
1297
1298.. method:: Logger.isEnabledFor(lvl)
1299
1300 Indicates if a message of severity *lvl* would be processed by this logger.
1301 This method checks first the module-level level set by
1302 ``logging.disable(lvl)`` and then the logger's effective level as determined
1303 by :meth:`getEffectiveLevel`.
1304
1305
1306.. method:: Logger.getEffectiveLevel()
1307
1308 Indicates the effective level for this logger. If a value other than
1309 :const:`NOTSET` has been set using :meth:`setLevel`, it is returned. Otherwise,
1310 the hierarchy is traversed towards the root until a value other than
1311 :const:`NOTSET` is found, and that value is returned.
1312
1313
Benjamin Peterson22005fc2010-04-11 16:25:06 +00001314.. method:: Logger.getChild(suffix)
1315
1316 Returns a logger which is a descendant to this logger, as determined by the suffix.
1317 Thus, ``logging.getLogger('abc').getChild('def.ghi')`` would return the same
1318 logger as would be returned by ``logging.getLogger('abc.def.ghi')``. This is a
1319 convenience method, useful when the parent logger is named using e.g. ``__name__``
1320 rather than a literal string.
1321
1322 .. versionadded:: 3.2
1323
Georg Brandl67b21b72010-08-17 15:07:14 +00001324
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001325.. method:: Logger.debug(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001326
1327 Logs a message with level :const:`DEBUG` on this logger. The *msg* is the
1328 message format string, and the *args* are the arguments which are merged into
1329 *msg* using the string formatting operator. (Note that this means that you can
1330 use keywords in the format string, together with a single dictionary argument.)
1331
Vinay Sajip8593ae62010-11-14 21:33:04 +00001332 There are three keyword arguments in *kwargs* which are inspected: *exc_info*
Georg Brandl116aa622007-08-15 14:28:22 +00001333 which, if it does not evaluate as false, causes exception information to be
1334 added to the logging message. If an exception tuple (in the format returned by
1335 :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
1336 is called to get the exception information.
1337
Vinay Sajip8593ae62010-11-14 21:33:04 +00001338 The second optional keyword argument is *stack_info*, which defaults to
1339 False. If specified as True, stack information is added to the logging
1340 message, including the actual logging call. Note that this is not the same
1341 stack information as that displayed through specifying *exc_info*: The
1342 former is stack frames from the bottom of the stack up to the logging call
1343 in the current thread, whereas the latter is information about stack frames
1344 which have been unwound, following an exception, while searching for
1345 exception handlers.
1346
1347 You can specify *stack_info* independently of *exc_info*, e.g. to just show
1348 how you got to a certain point in your code, even when no exceptions were
1349 raised. The stack frames are printed following a header line which says::
1350
1351 Stack (most recent call last):
1352
1353 This mimics the `Traceback (most recent call last):` which is used when
1354 displaying exception frames.
1355
1356 The third keyword argument is *extra* which can be used to pass a
Georg Brandl116aa622007-08-15 14:28:22 +00001357 dictionary which is used to populate the __dict__ of the LogRecord created for
1358 the logging event with user-defined attributes. These custom attributes can then
1359 be used as you like. For example, they could be incorporated into logged
1360 messages. For example::
1361
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001362 FORMAT = '%(asctime)-15s %(clientip)s %(user)-8s %(message)s'
Georg Brandl116aa622007-08-15 14:28:22 +00001363 logging.basicConfig(format=FORMAT)
Georg Brandl9afde1c2007-11-01 20:32:30 +00001364 d = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001365 logger = logging.getLogger('tcpserver')
1366 logger.warning('Protocol problem: %s', 'connection reset', extra=d)
Georg Brandl116aa622007-08-15 14:28:22 +00001367
1368 would print something like ::
1369
1370 2006-02-08 22:20:02,165 192.168.0.1 fbloggs Protocol problem: connection reset
1371
1372 The keys in the dictionary passed in *extra* should not clash with the keys used
1373 by the logging system. (See the :class:`Formatter` documentation for more
1374 information on which keys are used by the logging system.)
1375
1376 If you choose to use these attributes in logged messages, you need to exercise
1377 some care. In the above example, for instance, the :class:`Formatter` has been
1378 set up with a format string which expects 'clientip' and 'user' in the attribute
1379 dictionary of the LogRecord. If these are missing, the message will not be
1380 logged because a string formatting exception will occur. So in this case, you
1381 always need to pass the *extra* dictionary with these keys.
1382
1383 While this might be annoying, this feature is intended for use in specialized
1384 circumstances, such as multi-threaded servers where the same code executes in
1385 many contexts, and interesting conditions which arise are dependent on this
1386 context (such as remote client IP address and authenticated user name, in the
1387 above example). In such circumstances, it is likely that specialized
1388 :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
1389
Vinay Sajip8593ae62010-11-14 21:33:04 +00001390 .. versionadded:: 3.2
1391 The *stack_info* parameter was added.
1392
Georg Brandl116aa622007-08-15 14:28:22 +00001393
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001394.. method:: Logger.info(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001395
1396 Logs a message with level :const:`INFO` on this logger. The arguments are
1397 interpreted as for :meth:`debug`.
1398
1399
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001400.. method:: Logger.warning(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001401
1402 Logs a message with level :const:`WARNING` on this logger. The arguments are
1403 interpreted as for :meth:`debug`.
1404
1405
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001406.. method:: Logger.error(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001407
1408 Logs a message with level :const:`ERROR` on this logger. The arguments are
1409 interpreted as for :meth:`debug`.
1410
1411
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001412.. method:: Logger.critical(msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001413
1414 Logs a message with level :const:`CRITICAL` on this logger. The arguments are
1415 interpreted as for :meth:`debug`.
1416
1417
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001418.. method:: Logger.log(lvl, msg, *args, **kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +00001419
1420 Logs a message with integer level *lvl* on this logger. The other arguments are
1421 interpreted as for :meth:`debug`.
1422
1423
Georg Brandlcd7f32b2009-06-08 09:13:45 +00001424.. method:: Logger.exception(msg, *args)
Georg Brandl116aa622007-08-15 14:28:22 +00001425
1426 Logs a message with level :const:`ERROR` on this logger. The arguments are
1427 interpreted as for :meth:`debug`. Exception info is added to the logging
1428 message. This method should only be called from an exception handler.
1429
1430
1431.. method:: Logger.addFilter(filt)
1432
1433 Adds the specified filter *filt* to this logger.
1434
1435
1436.. method:: Logger.removeFilter(filt)
1437
1438 Removes the specified filter *filt* from this logger.
1439
1440
1441.. method:: Logger.filter(record)
1442
1443 Applies this logger's filters to the record and returns a true value if the
1444 record is to be processed.
1445
1446
1447.. method:: Logger.addHandler(hdlr)
1448
1449 Adds the specified handler *hdlr* to this logger.
1450
1451
1452.. method:: Logger.removeHandler(hdlr)
1453
1454 Removes the specified handler *hdlr* from this logger.
1455
1456
Vinay Sajip8593ae62010-11-14 21:33:04 +00001457.. method:: Logger.findCaller(stack_info=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001458
1459 Finds the caller's source filename and line number. Returns the filename, line
Vinay Sajip8593ae62010-11-14 21:33:04 +00001460 number, function name and stack information as a 4-element tuple. The stack
1461 information is returned as *None* unless *stack_info* is *True*.
Georg Brandl116aa622007-08-15 14:28:22 +00001462
Georg Brandl116aa622007-08-15 14:28:22 +00001463
1464.. method:: Logger.handle(record)
1465
1466 Handles a record by passing it to all handlers associated with this logger and
1467 its ancestors (until a false value of *propagate* is found). This method is used
1468 for unpickled records received from a socket, as well as those created locally.
Georg Brandl502d9a52009-07-26 15:02:41 +00001469 Logger-level filtering is applied using :meth:`~Logger.filter`.
Georg Brandl116aa622007-08-15 14:28:22 +00001470
1471
Vinay Sajip8593ae62010-11-14 21:33:04 +00001472.. method:: Logger.makeRecord(name, lvl, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001473
1474 This is a factory method which can be overridden in subclasses to create
1475 specialized :class:`LogRecord` instances.
1476
Vinay Sajip83eadd12010-09-20 10:31:18 +00001477.. method:: Logger.hasHandlers()
1478
1479 Checks to see if this logger has any handlers configured. This is done by
1480 looking for handlers in this logger and its parents in the logger hierarchy.
1481 Returns True if a handler was found, else False. The method stops searching
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001482 up the hierarchy whenever a logger with the 'propagate' attribute set to
Vinay Sajip83eadd12010-09-20 10:31:18 +00001483 False is found - that will be the last logger which is checked for the
1484 existence of handlers.
1485
Georg Brandl1eb40bc2010-12-03 15:30:09 +00001486 .. versionadded:: 3.2
Vinay Sajip83eadd12010-09-20 10:31:18 +00001487
Vinay Sajipa18b9592010-12-12 13:20:55 +00001488.. _basic-example:
Georg Brandl116aa622007-08-15 14:28:22 +00001489
1490Basic example
1491-------------
1492
Georg Brandl116aa622007-08-15 14:28:22 +00001493The :mod:`logging` package provides a lot of flexibility, and its configuration
1494can appear daunting. This section demonstrates that simple use of the logging
1495package is possible.
1496
1497The simplest example shows logging to the console::
1498
1499 import logging
1500
1501 logging.debug('A debug message')
1502 logging.info('Some information')
1503 logging.warning('A shot across the bows')
1504
1505If you run the above script, you'll see this::
1506
1507 WARNING:root:A shot across the bows
1508
1509Because no particular logger was specified, the system used the root logger. The
1510debug and info messages didn't appear because by default, the root logger is
1511configured to only handle messages with a severity of WARNING or above. The
1512message format is also a configuration default, as is the output destination of
1513the messages - ``sys.stderr``. The severity level, the message format and
1514destination can be easily changed, as shown in the example below::
1515
1516 import logging
1517
1518 logging.basicConfig(level=logging.DEBUG,
1519 format='%(asctime)s %(levelname)s %(message)s',
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001520 filename='myapp.log',
Georg Brandl116aa622007-08-15 14:28:22 +00001521 filemode='w')
1522 logging.debug('A debug message')
1523 logging.info('Some information')
1524 logging.warning('A shot across the bows')
1525
1526The :meth:`basicConfig` method is used to change the configuration defaults,
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00001527which results in output (written to ``myapp.log``) which should look
Georg Brandl116aa622007-08-15 14:28:22 +00001528something like the following::
1529
1530 2004-07-02 13:00:08,743 DEBUG A debug message
1531 2004-07-02 13:00:08,743 INFO Some information
1532 2004-07-02 13:00:08,743 WARNING A shot across the bows
1533
1534This time, all messages with a severity of DEBUG or above were handled, and the
1535format of the messages was also changed, and output went to the specified file
1536rather than the console.
1537
Georg Brandl81ac1ce2007-08-31 17:17:17 +00001538.. XXX logging should probably be updated for new string formatting!
Georg Brandl4b491312007-08-31 09:22:56 +00001539
1540Formatting uses the old Python string formatting - see section
1541:ref:`old-string-formatting`. The format string takes the following common
Georg Brandl116aa622007-08-15 14:28:22 +00001542specifiers. For a complete list of specifiers, consult the :class:`Formatter`
1543documentation.
1544
1545+-------------------+-----------------------------------------------+
1546| Format | Description |
1547+===================+===============================================+
1548| ``%(name)s`` | Name of the logger (logging channel). |
1549+-------------------+-----------------------------------------------+
1550| ``%(levelname)s`` | Text logging level for the message |
1551| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
1552| | ``'ERROR'``, ``'CRITICAL'``). |
1553+-------------------+-----------------------------------------------+
1554| ``%(asctime)s`` | Human-readable time when the |
1555| | :class:`LogRecord` was created. By default |
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001556| | this is of the form '2003-07-08 16:49:45,896' |
Georg Brandl116aa622007-08-15 14:28:22 +00001557| | (the numbers after the comma are millisecond |
1558| | portion of the time). |
1559+-------------------+-----------------------------------------------+
1560| ``%(message)s`` | The logged message. |
1561+-------------------+-----------------------------------------------+
1562
1563To change the date/time format, you can pass an additional keyword parameter,
1564*datefmt*, as in the following::
1565
1566 import logging
1567
1568 logging.basicConfig(level=logging.DEBUG,
1569 format='%(asctime)s %(levelname)-8s %(message)s',
1570 datefmt='%a, %d %b %Y %H:%M:%S',
1571 filename='/temp/myapp.log',
1572 filemode='w')
1573 logging.debug('A debug message')
1574 logging.info('Some information')
1575 logging.warning('A shot across the bows')
1576
1577which would result in output like ::
1578
1579 Fri, 02 Jul 2004 13:06:18 DEBUG A debug message
1580 Fri, 02 Jul 2004 13:06:18 INFO Some information
1581 Fri, 02 Jul 2004 13:06:18 WARNING A shot across the bows
1582
1583The date format string follows the requirements of :func:`strftime` - see the
1584documentation for the :mod:`time` module.
1585
1586If, instead of sending logging output to the console or a file, you'd rather use
1587a file-like object which you have created separately, you can pass it to
1588:func:`basicConfig` using the *stream* keyword argument. Note that if both
1589*stream* and *filename* keyword arguments are passed, the *stream* argument is
1590ignored.
1591
1592Of course, you can put variable information in your output. To do this, simply
1593have the message be a format string and pass in additional arguments containing
1594the variable information, as in the following example::
1595
1596 import logging
1597
1598 logging.basicConfig(level=logging.DEBUG,
1599 format='%(asctime)s %(levelname)-8s %(message)s',
1600 datefmt='%a, %d %b %Y %H:%M:%S',
1601 filename='/temp/myapp.log',
1602 filemode='w')
1603 logging.error('Pack my box with %d dozen %s', 5, 'liquor jugs')
1604
1605which would result in ::
1606
1607 Wed, 21 Jul 2004 15:35:16 ERROR Pack my box with 5 dozen liquor jugs
1608
1609
Vinay Sajipa18b9592010-12-12 13:20:55 +00001610Using file rotation
1611^^^^^^^^^^^^^^^^^^^
1612
1613.. sectionauthor:: Doug Hellmann, Vinay Sajip (changes)
1614.. (see <http://blog.doughellmann.com/2007/05/pymotw-logging.html>)
1615
1616Sometimes you want to let a log file grow to a certain size, then open a new
1617file and log to that. You may want to keep a certain number of these files, and
1618when that many files have been created, rotate the files so that the number of
1619files and the size of the files both remin bounded. For this usage pattern, the
1620logging package provides a :class:`RotatingFileHandler`::
1621
1622 import glob
1623 import logging
1624 import logging.handlers
1625
1626 LOG_FILENAME = 'logging_rotatingfile_example.out'
1627
1628 # Set up a specific logger with our desired output level
1629 my_logger = logging.getLogger('MyLogger')
1630 my_logger.setLevel(logging.DEBUG)
1631
1632 # Add the log message handler to the logger
1633 handler = logging.handlers.RotatingFileHandler(
1634 LOG_FILENAME, maxBytes=20, backupCount=5)
1635
1636 my_logger.addHandler(handler)
1637
1638 # Log some messages
1639 for i in range(20):
1640 my_logger.debug('i = %d' % i)
1641
1642 # See what files are created
1643 logfiles = glob.glob('%s*' % LOG_FILENAME)
1644
1645 for filename in logfiles:
1646 print(filename)
1647
1648The result should be 6 separate files, each with part of the log history for the
1649application::
1650
1651 logging_rotatingfile_example.out
1652 logging_rotatingfile_example.out.1
1653 logging_rotatingfile_example.out.2
1654 logging_rotatingfile_example.out.3
1655 logging_rotatingfile_example.out.4
1656 logging_rotatingfile_example.out.5
1657
1658The most current file is always :file:`logging_rotatingfile_example.out`,
1659and each time it reaches the size limit it is renamed with the suffix
1660``.1``. Each of the existing backup files is renamed to increment the suffix
1661(``.1`` becomes ``.2``, etc.) and the ``.6`` file is erased.
1662
1663Obviously this example sets the log length much much too small as an extreme
1664example. You would want to set *maxBytes* to an appropriate value.
1665
1666
1667The logger, handler, and log message call each specify a level. The log message
1668is only emitted if the handler and logger are configured to emit messages of
1669that level or lower. For example, if a message is ``CRITICAL``, and the logger
1670is set to ``ERROR``, the message is emitted. If a message is a ``WARNING``, and
1671the logger is set to produce only ``ERROR``\s, the message is not emitted::
1672
1673 import logging
1674 import sys
1675
1676 LEVELS = {'debug': logging.DEBUG,
1677 'info': logging.INFO,
1678 'warning': logging.WARNING,
1679 'error': logging.ERROR,
1680 'critical': logging.CRITICAL}
1681
1682 if len(sys.argv) > 1:
1683 level_name = sys.argv[1]
1684 level = LEVELS.get(level_name, logging.NOTSET)
1685 logging.basicConfig(level=level)
1686
1687 logging.debug('This is a debug message')
1688 logging.info('This is an info message')
1689 logging.warning('This is a warning message')
1690 logging.error('This is an error message')
1691 logging.critical('This is a critical error message')
1692
1693Run the script with an argument like 'debug' or 'warning' to see which messages
1694show up at different levels::
1695
1696 $ python logging_level_example.py debug
1697 DEBUG:root:This is a debug message
1698 INFO:root:This is an info message
1699 WARNING:root:This is a warning message
1700 ERROR:root:This is an error message
1701 CRITICAL:root:This is a critical error message
1702
1703 $ python logging_level_example.py info
1704 INFO:root:This is an info message
1705 WARNING:root:This is a warning message
1706 ERROR:root:This is an error message
1707 CRITICAL:root:This is a critical error message
1708
1709You will notice that these log messages all have ``root`` embedded in them. The
1710logging module supports a hierarchy of loggers with different names. An easy
1711way to tell where a specific log message comes from is to use a separate logger
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001712object for each of your modules. Each new logger 'inherits' the configuration
Vinay Sajipa18b9592010-12-12 13:20:55 +00001713of its parent, and log messages sent to a logger include the name of that
1714logger. Optionally, each logger can be configured differently, so that messages
1715from different modules are handled in different ways. Let's look at a simple
1716example of how to log from different modules so it is easy to trace the source
1717of the message::
1718
1719 import logging
1720
1721 logging.basicConfig(level=logging.WARNING)
1722
1723 logger1 = logging.getLogger('package1.module1')
1724 logger2 = logging.getLogger('package2.module2')
1725
1726 logger1.warning('This message comes from one module')
1727 logger2.warning('And this message comes from another module')
1728
1729And the output::
1730
1731 $ python logging_modules_example.py
1732 WARNING:package1.module1:This message comes from one module
1733 WARNING:package2.module2:And this message comes from another module
1734
1735There are many more options for configuring logging, including different log
1736message formatting options, having messages delivered to multiple destinations,
1737and changing the configuration of a long-running application on the fly using a
1738socket interface. All of these options are covered in depth in the library
1739module documentation.
1740
1741
Georg Brandl116aa622007-08-15 14:28:22 +00001742.. _multiple-destinations:
1743
1744Logging to multiple destinations
1745--------------------------------
1746
1747Let's say you want to log to console and file with different message formats and
1748in differing circumstances. Say you want to log messages with levels of DEBUG
1749and higher to file, and those messages at level INFO and higher to the console.
1750Let's also assume that the file should contain timestamps, but the console
1751messages should not. Here's how you can achieve this::
1752
1753 import logging
1754
1755 # set up logging to file - see previous section for more details
1756 logging.basicConfig(level=logging.DEBUG,
1757 format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
1758 datefmt='%m-%d %H:%M',
1759 filename='/temp/myapp.log',
1760 filemode='w')
1761 # define a Handler which writes INFO messages or higher to the sys.stderr
1762 console = logging.StreamHandler()
1763 console.setLevel(logging.INFO)
1764 # set a format which is simpler for console use
1765 formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
1766 # tell the handler to use this format
1767 console.setFormatter(formatter)
1768 # add the handler to the root logger
1769 logging.getLogger('').addHandler(console)
1770
1771 # Now, we can log to the root logger, or any other logger. First the root...
1772 logging.info('Jackdaws love my big sphinx of quartz.')
1773
1774 # Now, define a couple of other loggers which might represent areas in your
1775 # application:
1776
1777 logger1 = logging.getLogger('myapp.area1')
1778 logger2 = logging.getLogger('myapp.area2')
1779
1780 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
1781 logger1.info('How quickly daft jumping zebras vex.')
1782 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
1783 logger2.error('The five boxing wizards jump quickly.')
1784
1785When you run this, on the console you will see ::
1786
1787 root : INFO Jackdaws love my big sphinx of quartz.
1788 myapp.area1 : INFO How quickly daft jumping zebras vex.
1789 myapp.area2 : WARNING Jail zesty vixen who grabbed pay from quack.
1790 myapp.area2 : ERROR The five boxing wizards jump quickly.
1791
1792and in the file you will see something like ::
1793
1794 10-22 22:19 root INFO Jackdaws love my big sphinx of quartz.
1795 10-22 22:19 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
1796 10-22 22:19 myapp.area1 INFO How quickly daft jumping zebras vex.
1797 10-22 22:19 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
1798 10-22 22:19 myapp.area2 ERROR The five boxing wizards jump quickly.
1799
1800As you can see, the DEBUG message only shows up in the file. The other messages
1801are sent to both destinations.
1802
1803This example uses console and file handlers, but you can use any number and
1804combination of handlers you choose.
1805
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001806.. _logging-exceptions:
1807
1808Exceptions raised during logging
1809--------------------------------
1810
1811The logging package is designed to swallow exceptions which occur while logging
1812in production. This is so that errors which occur while handling logging events
1813- such as logging misconfiguration, network or other similar errors - do not
1814cause the application using logging to terminate prematurely.
1815
1816:class:`SystemExit` and :class:`KeyboardInterrupt` exceptions are never
1817swallowed. Other exceptions which occur during the :meth:`emit` method of a
1818:class:`Handler` subclass are passed to its :meth:`handleError` method.
1819
1820The default implementation of :meth:`handleError` in :class:`Handler` checks
Georg Brandlef871f62010-03-12 10:06:40 +00001821to see if a module-level variable, :data:`raiseExceptions`, is set. If set, a
1822traceback is printed to :data:`sys.stderr`. If not set, the exception is swallowed.
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001823
Georg Brandlef871f62010-03-12 10:06:40 +00001824**Note:** The default value of :data:`raiseExceptions` is ``True``. This is because
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001825during development, you typically want to be notified of any exceptions that
Georg Brandlef871f62010-03-12 10:06:40 +00001826occur. It's advised that you set :data:`raiseExceptions` to ``False`` for production
Vinay Sajip3ee22ec2009-08-20 22:05:10 +00001827usage.
Georg Brandl116aa622007-08-15 14:28:22 +00001828
Christian Heimes790c8232008-01-07 21:14:23 +00001829.. _context-info:
1830
1831Adding contextual information to your logging output
1832----------------------------------------------------
1833
1834Sometimes you want logging output to contain contextual information in
1835addition to the parameters passed to the logging call. For example, in a
1836networked application, it may be desirable to log client-specific information
1837in the log (e.g. remote client's username, or IP address). Although you could
1838use the *extra* parameter to achieve this, it's not always convenient to pass
1839the information in this way. While it might be tempting to create
1840:class:`Logger` instances on a per-connection basis, this is not a good idea
1841because these instances are not garbage collected. While this is not a problem
1842in practice, when the number of :class:`Logger` instances is dependent on the
1843level of granularity you want to use in logging an application, it could
1844be hard to manage if the number of :class:`Logger` instances becomes
1845effectively unbounded.
1846
Vinay Sajipc31be632010-09-06 22:18:20 +00001847
1848Using LoggerAdapters to impart contextual information
1849^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1850
Christian Heimes04c420f2008-01-18 18:40:46 +00001851An easy way in which you can pass contextual information to be output along
1852with logging event information is to use the :class:`LoggerAdapter` class.
1853This class is designed to look like a :class:`Logger`, so that you can call
1854:meth:`debug`, :meth:`info`, :meth:`warning`, :meth:`error`,
1855:meth:`exception`, :meth:`critical` and :meth:`log`. These methods have the
1856same signatures as their counterparts in :class:`Logger`, so you can use the
1857two types of instances interchangeably.
Christian Heimes790c8232008-01-07 21:14:23 +00001858
Christian Heimes04c420f2008-01-18 18:40:46 +00001859When you create an instance of :class:`LoggerAdapter`, you pass it a
1860:class:`Logger` instance and a dict-like object which contains your contextual
1861information. When you call one of the logging methods on an instance of
1862:class:`LoggerAdapter`, it delegates the call to the underlying instance of
1863:class:`Logger` passed to its constructor, and arranges to pass the contextual
1864information in the delegated call. Here's a snippet from the code of
1865:class:`LoggerAdapter`::
Christian Heimes790c8232008-01-07 21:14:23 +00001866
Christian Heimes04c420f2008-01-18 18:40:46 +00001867 def debug(self, msg, *args, **kwargs):
1868 """
1869 Delegate a debug call to the underlying logger, after adding
1870 contextual information from this adapter instance.
1871 """
1872 msg, kwargs = self.process(msg, kwargs)
1873 self.logger.debug(msg, *args, **kwargs)
Christian Heimes790c8232008-01-07 21:14:23 +00001874
Christian Heimes04c420f2008-01-18 18:40:46 +00001875The :meth:`process` method of :class:`LoggerAdapter` is where the contextual
1876information is added to the logging output. It's passed the message and
1877keyword arguments of the logging call, and it passes back (potentially)
1878modified versions of these to use in the call to the underlying logger. The
1879default implementation of this method leaves the message alone, but inserts
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001880an 'extra' key in the keyword argument whose value is the dict-like object
1881passed to the constructor. Of course, if you had passed an 'extra' keyword
Christian Heimes04c420f2008-01-18 18:40:46 +00001882argument in the call to the adapter, it will be silently overwritten.
Christian Heimes790c8232008-01-07 21:14:23 +00001883
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001884The advantage of using 'extra' is that the values in the dict-like object are
Christian Heimes04c420f2008-01-18 18:40:46 +00001885merged into the :class:`LogRecord` instance's __dict__, allowing you to use
1886customized strings with your :class:`Formatter` instances which know about
1887the keys of the dict-like object. If you need a different method, e.g. if you
1888want to prepend or append the contextual information to the message string,
1889you just need to subclass :class:`LoggerAdapter` and override :meth:`process`
1890to do what you need. Here's an example script which uses this class, which
1891also illustrates what dict-like behaviour is needed from an arbitrary
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001892'dict-like' object for use in the constructor::
Christian Heimes04c420f2008-01-18 18:40:46 +00001893
Christian Heimes587c2bf2008-01-19 16:21:02 +00001894 import logging
Georg Brandl86def6c2008-01-21 20:36:10 +00001895
Christian Heimes587c2bf2008-01-19 16:21:02 +00001896 class ConnInfo:
1897 """
1898 An example class which shows how an arbitrary class can be used as
1899 the 'extra' context information repository passed to a LoggerAdapter.
1900 """
Georg Brandl86def6c2008-01-21 20:36:10 +00001901
Christian Heimes587c2bf2008-01-19 16:21:02 +00001902 def __getitem__(self, name):
1903 """
1904 To allow this instance to look like a dict.
1905 """
1906 from random import choice
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001907 if name == 'ip':
1908 result = choice(['127.0.0.1', '192.168.0.1'])
1909 elif name == 'user':
1910 result = choice(['jim', 'fred', 'sheila'])
Christian Heimes587c2bf2008-01-19 16:21:02 +00001911 else:
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001912 result = self.__dict__.get(name, '?')
Christian Heimes587c2bf2008-01-19 16:21:02 +00001913 return result
Georg Brandl86def6c2008-01-21 20:36:10 +00001914
Christian Heimes587c2bf2008-01-19 16:21:02 +00001915 def __iter__(self):
1916 """
1917 To allow iteration over keys, which will be merged into
1918 the LogRecord dict before formatting and output.
1919 """
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001920 keys = ['ip', 'user']
Christian Heimes587c2bf2008-01-19 16:21:02 +00001921 keys.extend(self.__dict__.keys())
1922 return keys.__iter__()
Georg Brandl86def6c2008-01-21 20:36:10 +00001923
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001924 if __name__ == '__main__':
Christian Heimes587c2bf2008-01-19 16:21:02 +00001925 from random import choice
1926 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001927 a1 = logging.LoggerAdapter(logging.getLogger('a.b.c'),
1928 { 'ip' : '123.231.231.123', 'user' : 'sheila' })
Christian Heimes587c2bf2008-01-19 16:21:02 +00001929 logging.basicConfig(level=logging.DEBUG,
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001930 format='%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s')
1931 a1.debug('A debug message')
1932 a1.info('An info message with %s', 'some parameters')
1933 a2 = logging.LoggerAdapter(logging.getLogger('d.e.f'), ConnInfo())
Christian Heimes587c2bf2008-01-19 16:21:02 +00001934 for x in range(10):
1935 lvl = choice(levels)
1936 lvlname = logging.getLevelName(lvl)
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001937 a2.log(lvl, 'A message at %s level with %d %s', lvlname, 2, 'parameters')
Christian Heimes04c420f2008-01-18 18:40:46 +00001938
1939When this script is run, the output should look something like this::
1940
Christian Heimes587c2bf2008-01-19 16:21:02 +00001941 2008-01-18 14:49:54,023 a.b.c DEBUG IP: 123.231.231.123 User: sheila A debug message
1942 2008-01-18 14:49:54,023 a.b.c INFO IP: 123.231.231.123 User: sheila An info message with some parameters
1943 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
1944 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
1945 2008-01-18 14:49:54,033 d.e.f WARNING IP: 192.168.0.1 User: sheila A message at WARNING level with 2 parameters
1946 2008-01-18 14:49:54,033 d.e.f ERROR IP: 127.0.0.1 User: fred A message at ERROR level with 2 parameters
1947 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
1948 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
1949 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
1950 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
1951 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
1952 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 +00001953
Christian Heimes790c8232008-01-07 21:14:23 +00001954
Vinay Sajipac007992010-09-17 12:45:26 +00001955.. _filters-contextual:
1956
Vinay Sajipc31be632010-09-06 22:18:20 +00001957Using Filters to impart contextual information
1958^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1959
1960You can also add contextual information to log output using a user-defined
1961:class:`Filter`. ``Filter`` instances are allowed to modify the ``LogRecords``
1962passed to them, including adding additional attributes which can then be output
1963using a suitable format string, or if needed a custom :class:`Formatter`.
1964
1965For example in a web application, the request being processed (or at least,
1966the interesting parts of it) can be stored in a threadlocal
1967(:class:`threading.local`) variable, and then accessed from a ``Filter`` to
1968add, say, information from the request - say, the remote IP address and remote
1969user's username - to the ``LogRecord``, using the attribute names 'ip' and
1970'user' as in the ``LoggerAdapter`` example above. In that case, the same format
1971string can be used to get similar output to that shown above. Here's an example
1972script::
1973
1974 import logging
1975 from random import choice
1976
1977 class ContextFilter(logging.Filter):
1978 """
1979 This is a filter which injects contextual information into the log.
1980
1981 Rather than use actual contextual information, we just use random
1982 data in this demo.
1983 """
1984
1985 USERS = ['jim', 'fred', 'sheila']
1986 IPS = ['123.231.231.123', '127.0.0.1', '192.168.0.1']
1987
1988 def filter(self, record):
1989
1990 record.ip = choice(ContextFilter.IPS)
1991 record.user = choice(ContextFilter.USERS)
1992 return True
1993
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001994 if __name__ == '__main__':
Vinay Sajipc31be632010-09-06 22:18:20 +00001995 levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001996 a1 = logging.LoggerAdapter(logging.getLogger('a.b.c'),
1997 { 'ip' : '123.231.231.123', 'user' : 'sheila' })
Vinay Sajipc31be632010-09-06 22:18:20 +00001998 logging.basicConfig(level=logging.DEBUG,
Vinay Sajip9a6b4002010-12-14 19:40:21 +00001999 format='%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s')
2000 a1 = logging.getLogger('a.b.c')
2001 a2 = logging.getLogger('d.e.f')
Vinay Sajipc31be632010-09-06 22:18:20 +00002002
2003 f = ContextFilter()
2004 a1.addFilter(f)
2005 a2.addFilter(f)
Vinay Sajip9a6b4002010-12-14 19:40:21 +00002006 a1.debug('A debug message')
2007 a1.info('An info message with %s', 'some parameters')
Vinay Sajipc31be632010-09-06 22:18:20 +00002008 for x in range(10):
2009 lvl = choice(levels)
2010 lvlname = logging.getLevelName(lvl)
Vinay Sajip9a6b4002010-12-14 19:40:21 +00002011 a2.log(lvl, 'A message at %s level with %d %s', lvlname, 2, 'parameters')
Vinay Sajipc31be632010-09-06 22:18:20 +00002012
2013which, when run, produces something like::
2014
2015 2010-09-06 22:38:15,292 a.b.c DEBUG IP: 123.231.231.123 User: fred A debug message
2016 2010-09-06 22:38:15,300 a.b.c INFO IP: 192.168.0.1 User: sheila An info message with some parameters
2017 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
2018 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
2019 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
2020 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
2021 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
2022 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
2023 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
2024 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
2025 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
2026 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
2027
2028
Vinay Sajipd31f3632010-06-29 15:31:15 +00002029.. _multiple-processes:
2030
Vinay Sajipa7471bf2009-08-15 23:23:37 +00002031Logging to a single file from multiple processes
2032------------------------------------------------
2033
2034Although logging is thread-safe, and logging to a single file from multiple
2035threads in a single process *is* supported, logging to a single file from
2036*multiple processes* is *not* supported, because there is no standard way to
2037serialize access to a single file across multiple processes in Python. If you
Vinay Sajip121a1c42010-09-08 10:46:15 +00002038need to log to a single file from multiple processes, one way of doing this is
2039to have all the processes log to a :class:`SocketHandler`, and have a separate
2040process which implements a socket server which reads from the socket and logs
2041to file. (If you prefer, you can dedicate one thread in one of the existing
2042processes to perform this function.) The following section documents this
2043approach in more detail and includes a working socket receiver which can be
2044used as a starting point for you to adapt in your own applications.
Vinay Sajipa7471bf2009-08-15 23:23:37 +00002045
Vinay Sajip5a92b132009-08-15 23:35:08 +00002046If you are using a recent version of Python which includes the
Vinay Sajip121a1c42010-09-08 10:46:15 +00002047:mod:`multiprocessing` module, you could write your own handler which uses the
Vinay Sajip5a92b132009-08-15 23:35:08 +00002048:class:`Lock` class from this module to serialize access to the file from
2049your processes. The existing :class:`FileHandler` and subclasses do not make
2050use of :mod:`multiprocessing` at present, though they may do so in the future.
Vinay Sajip8c6b0a52009-08-17 13:17:47 +00002051Note that at present, the :mod:`multiprocessing` module does not provide
2052working lock functionality on all platforms (see
2053http://bugs.python.org/issue3770).
Vinay Sajip5a92b132009-08-15 23:35:08 +00002054
Vinay Sajip121a1c42010-09-08 10:46:15 +00002055.. currentmodule:: logging.handlers
2056
2057Alternatively, you can use a ``Queue`` and a :class:`QueueHandler` to send
2058all logging events to one of the processes in your multi-process application.
2059The following example script demonstrates how you can do this; in the example
2060a separate listener process listens for events sent by other processes and logs
2061them according to its own logging configuration. Although the example only
2062demonstrates one way of doing it (for example, you may want to use a listener
2063thread rather than a separate listener process - the implementation would be
2064analogous) it does allow for completely different logging configurations for
2065the listener and the other processes in your application, and can be used as
2066the basis for code meeting your own specific requirements::
2067
2068 # You'll need these imports in your own code
2069 import logging
2070 import logging.handlers
2071 import multiprocessing
2072
2073 # Next two import lines for this demo only
2074 from random import choice, random
2075 import time
2076
2077 #
2078 # Because you'll want to define the logging configurations for listener and workers, the
2079 # listener and worker process functions take a configurer parameter which is a callable
2080 # for configuring logging for that process. These functions are also passed the queue,
2081 # which they use for communication.
2082 #
2083 # In practice, you can configure the listener however you want, but note that in this
2084 # simple example, the listener does not apply level or filter logic to received records.
2085 # In practice, you would probably want to do ths logic in the worker processes, to avoid
2086 # sending events which would be filtered out between processes.
2087 #
2088 # The size of the rotated files is made small so you can see the results easily.
2089 def listener_configurer():
2090 root = logging.getLogger()
2091 h = logging.handlers.RotatingFileHandler('/tmp/mptest.log', 'a', 300, 10)
2092 f = logging.Formatter('%(asctime)s %(processName)-10s %(name)s %(levelname)-8s %(message)s')
2093 h.setFormatter(f)
2094 root.addHandler(h)
2095
2096 # This is the listener process top-level loop: wait for logging events
2097 # (LogRecords)on the queue and handle them, quit when you get a None for a
2098 # LogRecord.
2099 def listener_process(queue, configurer):
2100 configurer()
2101 while True:
2102 try:
2103 record = queue.get()
2104 if record is None: # We send this as a sentinel to tell the listener to quit.
2105 break
2106 logger = logging.getLogger(record.name)
2107 logger.handle(record) # No level or filter logic applied - just do it!
2108 except (KeyboardInterrupt, SystemExit):
2109 raise
2110 except:
2111 import sys, traceback
2112 print >> sys.stderr, 'Whoops! Problem:'
2113 traceback.print_exc(file=sys.stderr)
2114
2115 # Arrays used for random selections in this demo
2116
2117 LEVELS = [logging.DEBUG, logging.INFO, logging.WARNING,
2118 logging.ERROR, logging.CRITICAL]
2119
2120 LOGGERS = ['a.b.c', 'd.e.f']
2121
2122 MESSAGES = [
2123 'Random message #1',
2124 'Random message #2',
2125 'Random message #3',
2126 ]
2127
2128 # The worker configuration is done at the start of the worker process run.
2129 # Note that on Windows you can't rely on fork semantics, so each process
2130 # will run the logging configuration code when it starts.
2131 def worker_configurer(queue):
2132 h = logging.handlers.QueueHandler(queue) # Just the one handler needed
2133 root = logging.getLogger()
2134 root.addHandler(h)
2135 root.setLevel(logging.DEBUG) # send all messages, for demo; no other level or filter logic applied.
2136
2137 # This is the worker process top-level loop, which just logs ten events with
2138 # random intervening delays before terminating.
2139 # The print messages are just so you know it's doing something!
2140 def worker_process(queue, configurer):
2141 configurer(queue)
2142 name = multiprocessing.current_process().name
2143 print('Worker started: %s' % name)
2144 for i in range(10):
2145 time.sleep(random())
2146 logger = logging.getLogger(choice(LOGGERS))
2147 level = choice(LEVELS)
2148 message = choice(MESSAGES)
2149 logger.log(level, message)
2150 print('Worker finished: %s' % name)
2151
2152 # Here's where the demo gets orchestrated. Create the queue, create and start
2153 # the listener, create ten workers and start them, wait for them to finish,
2154 # then send a None to the queue to tell the listener to finish.
2155 def main():
2156 queue = multiprocessing.Queue(-1)
2157 listener = multiprocessing.Process(target=listener_process,
2158 args=(queue, listener_configurer))
2159 listener.start()
2160 workers = []
2161 for i in range(10):
2162 worker = multiprocessing.Process(target=worker_process,
2163 args=(queue, worker_configurer))
2164 workers.append(worker)
2165 worker.start()
2166 for w in workers:
2167 w.join()
2168 queue.put_nowait(None)
2169 listener.join()
2170
2171 if __name__ == '__main__':
2172 main()
2173
2174
2175.. currentmodule:: logging
2176
Benjamin Peterson8719ad52009-09-11 22:24:02 +00002177
Georg Brandl116aa622007-08-15 14:28:22 +00002178.. _network-logging:
2179
2180Sending and receiving logging events across a network
2181-----------------------------------------------------
2182
2183Let's say you want to send logging events across a network, and handle them at
2184the receiving end. A simple way of doing this is attaching a
2185:class:`SocketHandler` instance to the root logger at the sending end::
2186
2187 import logging, logging.handlers
2188
2189 rootLogger = logging.getLogger('')
2190 rootLogger.setLevel(logging.DEBUG)
2191 socketHandler = logging.handlers.SocketHandler('localhost',
2192 logging.handlers.DEFAULT_TCP_LOGGING_PORT)
2193 # don't bother with a formatter, since a socket handler sends the event as
2194 # an unformatted pickle
2195 rootLogger.addHandler(socketHandler)
2196
2197 # Now, we can log to the root logger, or any other logger. First the root...
2198 logging.info('Jackdaws love my big sphinx of quartz.')
2199
2200 # Now, define a couple of other loggers which might represent areas in your
2201 # application:
2202
2203 logger1 = logging.getLogger('myapp.area1')
2204 logger2 = logging.getLogger('myapp.area2')
2205
2206 logger1.debug('Quick zephyrs blow, vexing daft Jim.')
2207 logger1.info('How quickly daft jumping zebras vex.')
2208 logger2.warning('Jail zesty vixen who grabbed pay from quack.')
2209 logger2.error('The five boxing wizards jump quickly.')
2210
Alexandre Vassalottice261952008-05-12 02:31:37 +00002211At the receiving end, you can set up a receiver using the :mod:`socketserver`
Georg Brandl116aa622007-08-15 14:28:22 +00002212module. Here is a basic working example::
2213
Georg Brandla35f4b92009-05-31 16:41:59 +00002214 import pickle
Georg Brandl116aa622007-08-15 14:28:22 +00002215 import logging
2216 import logging.handlers
Alexandre Vassalottice261952008-05-12 02:31:37 +00002217 import socketserver
Georg Brandl116aa622007-08-15 14:28:22 +00002218 import struct
2219
2220
Alexandre Vassalottice261952008-05-12 02:31:37 +00002221 class LogRecordStreamHandler(socketserver.StreamRequestHandler):
Georg Brandl116aa622007-08-15 14:28:22 +00002222 """Handler for a streaming logging request.
2223
2224 This basically logs the record using whatever logging policy is
2225 configured locally.
2226 """
2227
2228 def handle(self):
2229 """
2230 Handle multiple requests - each expected to be a 4-byte length,
2231 followed by the LogRecord in pickle format. Logs the record
2232 according to whatever policy is configured locally.
2233 """
Collin Winter46334482007-09-10 00:49:57 +00002234 while True:
Georg Brandl116aa622007-08-15 14:28:22 +00002235 chunk = self.connection.recv(4)
2236 if len(chunk) < 4:
2237 break
Vinay Sajip9a6b4002010-12-14 19:40:21 +00002238 slen = struct.unpack('>L', chunk)[0]
Georg Brandl116aa622007-08-15 14:28:22 +00002239 chunk = self.connection.recv(slen)
2240 while len(chunk) < slen:
2241 chunk = chunk + self.connection.recv(slen - len(chunk))
2242 obj = self.unPickle(chunk)
2243 record = logging.makeLogRecord(obj)
2244 self.handleLogRecord(record)
2245
2246 def unPickle(self, data):
Georg Brandla35f4b92009-05-31 16:41:59 +00002247 return pickle.loads(data)
Georg Brandl116aa622007-08-15 14:28:22 +00002248
2249 def handleLogRecord(self, record):
2250 # if a name is specified, we use the named logger rather than the one
2251 # implied by the record.
2252 if self.server.logname is not None:
2253 name = self.server.logname
2254 else:
2255 name = record.name
2256 logger = logging.getLogger(name)
2257 # N.B. EVERY record gets logged. This is because Logger.handle
2258 # is normally called AFTER logger-level filtering. If you want
2259 # to do filtering, do it at the client end to save wasting
2260 # cycles and network bandwidth!
2261 logger.handle(record)
2262
Alexandre Vassalottice261952008-05-12 02:31:37 +00002263 class LogRecordSocketReceiver(socketserver.ThreadingTCPServer):
Vinay Sajip9a6b4002010-12-14 19:40:21 +00002264 """
2265 Simple TCP socket-based logging receiver suitable for testing.
Georg Brandl116aa622007-08-15 14:28:22 +00002266 """
2267
2268 allow_reuse_address = 1
2269
2270 def __init__(self, host='localhost',
2271 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
2272 handler=LogRecordStreamHandler):
Alexandre Vassalottice261952008-05-12 02:31:37 +00002273 socketserver.ThreadingTCPServer.__init__(self, (host, port), handler)
Georg Brandl116aa622007-08-15 14:28:22 +00002274 self.abort = 0
2275 self.timeout = 1
2276 self.logname = None
2277
2278 def serve_until_stopped(self):
2279 import select
2280 abort = 0
2281 while not abort:
2282 rd, wr, ex = select.select([self.socket.fileno()],
2283 [], [],
2284 self.timeout)
2285 if rd:
2286 self.handle_request()
2287 abort = self.abort
2288
2289 def main():
2290 logging.basicConfig(
Vinay Sajip9a6b4002010-12-14 19:40:21 +00002291 format='%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s')
Georg Brandl116aa622007-08-15 14:28:22 +00002292 tcpserver = LogRecordSocketReceiver()
Vinay Sajip9a6b4002010-12-14 19:40:21 +00002293 print('About to start TCP server...')
Georg Brandl116aa622007-08-15 14:28:22 +00002294 tcpserver.serve_until_stopped()
2295
Vinay Sajip9a6b4002010-12-14 19:40:21 +00002296 if __name__ == '__main__':
Georg Brandl116aa622007-08-15 14:28:22 +00002297 main()
2298
2299First run the server, and then the client. On the client side, nothing is
2300printed on the console; on the server side, you should see something like::
2301
2302 About to start TCP server...
2303 59 root INFO Jackdaws love my big sphinx of quartz.
2304 59 myapp.area1 DEBUG Quick zephyrs blow, vexing daft Jim.
2305 69 myapp.area1 INFO How quickly daft jumping zebras vex.
2306 69 myapp.area2 WARNING Jail zesty vixen who grabbed pay from quack.
2307 69 myapp.area2 ERROR The five boxing wizards jump quickly.
2308
Vinay Sajipc15dfd62010-07-06 15:08:55 +00002309Note that there are some security issues with pickle in some scenarios. If
2310these affect you, you can use an alternative serialization scheme by overriding
2311the :meth:`makePickle` method and implementing your alternative there, as
2312well as adapting the above script to use your alternative serialization.
2313
Vinay Sajip4039aff2010-09-11 10:25:28 +00002314.. _arbitrary-object-messages:
2315
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002316Using arbitrary objects as messages
2317-----------------------------------
2318
2319In the preceding sections and examples, it has been assumed that the message
2320passed when logging the event is a string. However, this is not the only
2321possibility. You can pass an arbitrary object as a message, and its
2322:meth:`__str__` method will be called when the logging system needs to convert
2323it to a string representation. In fact, if you want to, you can avoid
2324computing a string representation altogether - for example, the
2325:class:`SocketHandler` emits an event by pickling it and sending it over the
2326wire.
2327
Vinay Sajip55778922010-09-23 09:09:15 +00002328Dealing with handlers that block
2329--------------------------------
2330
2331.. currentmodule:: logging.handlers
2332
2333Sometimes you have to get your logging handlers to do their work without
2334blocking the thread you’re logging from. This is common in Web applications,
2335though of course it also occurs in other scenarios.
2336
2337A common culprit which demonstrates sluggish behaviour is the
2338:class:`SMTPHandler`: sending emails can take a long time, for a
2339number of reasons outside the developer’s control (for example, a poorly
2340performing mail or network infrastructure). But almost any network-based
2341handler can block: Even a :class:`SocketHandler` operation may do a
2342DNS query under the hood which is too slow (and this query can be deep in the
2343socket library code, below the Python layer, and outside your control).
2344
2345One solution is to use a two-part approach. For the first part, attach only a
2346:class:`QueueHandler` to those loggers which are accessed from
2347performance-critical threads. They simply write to their queue, which can be
2348sized to a large enough capacity or initialized with no upper bound to their
2349size. The write to the queue will typically be accepted quickly, though you
2350will probably need to catch the :ref:`queue.Full` exception as a precaution
2351in your code. If you are a library developer who has performance-critical
2352threads in their code, be sure to document this (together with a suggestion to
2353attach only ``QueueHandlers`` to your loggers) for the benefit of other
2354developers who will use your code.
2355
2356The second part of the solution is :class:`QueueListener`, which has been
2357designed as the counterpart to :class:`QueueHandler`. A
2358:class:`QueueListener` is very simple: it’s passed a queue and some handlers,
2359and it fires up an internal thread which listens to its queue for LogRecords
2360sent from ``QueueHandlers`` (or any other source of ``LogRecords``, for that
2361matter). The ``LogRecords`` are removed from the queue and passed to the
2362handlers for processing.
2363
2364The advantage of having a separate :class:`QueueListener` class is that you
2365can use the same instance to service multiple ``QueueHandlers``. This is more
2366resource-friendly than, say, having threaded versions of the existing handler
2367classes, which would eat up one thread per handler for no particular benefit.
2368
2369An example of using these two classes follows (imports omitted)::
2370
2371 que = queue.Queue(-1) # no limit on size
2372 queue_handler = QueueHandler(que)
2373 handler = logging.StreamHandler()
2374 listener = QueueListener(que, handler)
2375 root = logging.getLogger()
2376 root.addHandler(queue_handler)
2377 formatter = logging.Formatter('%(threadName)s: %(message)s')
2378 handler.setFormatter(formatter)
2379 listener.start()
2380 # The log output will display the thread which generated
2381 # the event (the main thread) rather than the internal
2382 # thread which monitors the internal queue. This is what
2383 # you want to happen.
2384 root.warning('Look out!')
2385 listener.stop()
2386
2387which, when run, will produce::
2388
2389 MainThread: Look out!
2390
2391
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002392Optimization
2393------------
2394
2395Formatting of message arguments is deferred until it cannot be avoided.
2396However, computing the arguments passed to the logging method can also be
2397expensive, and you may want to avoid doing it if the logger will just throw
2398away your event. To decide what to do, you can call the :meth:`isEnabledFor`
2399method which takes a level argument and returns true if the event would be
2400created by the Logger for that level of call. You can write code like this::
2401
2402 if logger.isEnabledFor(logging.DEBUG):
Vinay Sajip9a6b4002010-12-14 19:40:21 +00002403 logger.debug('Message with %s, %s', expensive_func1(),
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002404 expensive_func2())
2405
2406so that if the logger's threshold is set above ``DEBUG``, the calls to
2407:func:`expensive_func1` and :func:`expensive_func2` are never made.
2408
2409There are other optimizations which can be made for specific applications which
2410need more precise control over what logging information is collected. Here's a
2411list of things you can do to avoid processing during logging which you don't
2412need:
2413
2414+-----------------------------------------------+----------------------------------------+
2415| What you don't want to collect | How to avoid collecting it |
2416+===============================================+========================================+
2417| Information about where calls were made from. | Set ``logging._srcfile`` to ``None``. |
2418+-----------------------------------------------+----------------------------------------+
2419| Threading information. | Set ``logging.logThreads`` to ``0``. |
2420+-----------------------------------------------+----------------------------------------+
2421| Process information. | Set ``logging.logProcesses`` to ``0``. |
2422+-----------------------------------------------+----------------------------------------+
2423
2424Also note that the core logging module only includes the basic handlers. If
2425you don't import :mod:`logging.handlers` and :mod:`logging.config`, they won't
2426take up any memory.
2427
2428.. _handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002429
2430Handler Objects
2431---------------
2432
2433Handlers have the following attributes and methods. Note that :class:`Handler`
2434is never instantiated directly; this class acts as a base for more useful
2435subclasses. However, the :meth:`__init__` method in subclasses needs to call
2436:meth:`Handler.__init__`.
2437
2438
2439.. method:: Handler.__init__(level=NOTSET)
2440
2441 Initializes the :class:`Handler` instance by setting its level, setting the list
2442 of filters to the empty list and creating a lock (using :meth:`createLock`) for
2443 serializing access to an I/O mechanism.
2444
2445
2446.. method:: Handler.createLock()
2447
2448 Initializes a thread lock which can be used to serialize access to underlying
2449 I/O functionality which may not be threadsafe.
2450
2451
2452.. method:: Handler.acquire()
2453
2454 Acquires the thread lock created with :meth:`createLock`.
2455
2456
2457.. method:: Handler.release()
2458
2459 Releases the thread lock acquired with :meth:`acquire`.
2460
2461
2462.. method:: Handler.setLevel(lvl)
2463
2464 Sets the threshold for this handler to *lvl*. Logging messages which are less
2465 severe than *lvl* will be ignored. When a handler is created, the level is set
2466 to :const:`NOTSET` (which causes all messages to be processed).
2467
2468
2469.. method:: Handler.setFormatter(form)
2470
2471 Sets the :class:`Formatter` for this handler to *form*.
2472
2473
2474.. method:: Handler.addFilter(filt)
2475
2476 Adds the specified filter *filt* to this handler.
2477
2478
2479.. method:: Handler.removeFilter(filt)
2480
2481 Removes the specified filter *filt* from this handler.
2482
2483
2484.. method:: Handler.filter(record)
2485
2486 Applies this handler's filters to the record and returns a true value if the
2487 record is to be processed.
2488
2489
2490.. method:: Handler.flush()
2491
2492 Ensure all logging output has been flushed. This version does nothing and is
2493 intended to be implemented by subclasses.
2494
2495
2496.. method:: Handler.close()
2497
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002498 Tidy up any resources used by the handler. This version does no output but
2499 removes the handler from an internal list of handlers which is closed when
2500 :func:`shutdown` is called. Subclasses should ensure that this gets called
2501 from overridden :meth:`close` methods.
Georg Brandl116aa622007-08-15 14:28:22 +00002502
2503
2504.. method:: Handler.handle(record)
2505
2506 Conditionally emits the specified logging record, depending on filters which may
2507 have been added to the handler. Wraps the actual emission of the record with
2508 acquisition/release of the I/O thread lock.
2509
2510
2511.. method:: Handler.handleError(record)
2512
2513 This method should be called from handlers when an exception is encountered
2514 during an :meth:`emit` call. By default it does nothing, which means that
2515 exceptions get silently ignored. This is what is mostly wanted for a logging
2516 system - most users will not care about errors in the logging system, they are
2517 more interested in application errors. You could, however, replace this with a
2518 custom handler if you wish. The specified record is the one which was being
2519 processed when the exception occurred.
2520
2521
2522.. method:: Handler.format(record)
2523
2524 Do formatting for a record - if a formatter is set, use it. Otherwise, use the
2525 default formatter for the module.
2526
2527
2528.. method:: Handler.emit(record)
2529
2530 Do whatever it takes to actually log the specified logging record. This version
2531 is intended to be implemented by subclasses and so raises a
2532 :exc:`NotImplementedError`.
2533
2534
Vinay Sajipd31f3632010-06-29 15:31:15 +00002535.. _stream-handler:
2536
Georg Brandl116aa622007-08-15 14:28:22 +00002537StreamHandler
2538^^^^^^^^^^^^^
2539
2540The :class:`StreamHandler` class, located in the core :mod:`logging` package,
2541sends logging output to streams such as *sys.stdout*, *sys.stderr* or any
2542file-like object (or, more precisely, any object which supports :meth:`write`
2543and :meth:`flush` methods).
2544
2545
Benjamin Peterson1baf4652009-12-31 03:11:23 +00002546.. currentmodule:: logging
2547
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002548.. class:: StreamHandler(stream=None)
Georg Brandl116aa622007-08-15 14:28:22 +00002549
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +00002550 Returns a new instance of the :class:`StreamHandler` class. If *stream* is
Georg Brandl116aa622007-08-15 14:28:22 +00002551 specified, the instance will use it for logging output; otherwise, *sys.stderr*
2552 will be used.
2553
2554
Benjamin Petersone41251e2008-04-25 01:59:09 +00002555 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002556
Benjamin Petersone41251e2008-04-25 01:59:09 +00002557 If a formatter is specified, it is used to format the record. The record
2558 is then written to the stream with a trailing newline. If exception
2559 information is present, it is formatted using
2560 :func:`traceback.print_exception` and appended to the stream.
Georg Brandl116aa622007-08-15 14:28:22 +00002561
2562
Benjamin Petersone41251e2008-04-25 01:59:09 +00002563 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00002564
Benjamin Petersone41251e2008-04-25 01:59:09 +00002565 Flushes the stream by calling its :meth:`flush` method. Note that the
2566 :meth:`close` method is inherited from :class:`Handler` and so does
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00002567 no output, so an explicit :meth:`flush` call may be needed at times.
Georg Brandl116aa622007-08-15 14:28:22 +00002568
Vinay Sajip05ed6952010-10-20 20:34:09 +00002569.. versionchanged:: 3.2
2570 The ``StreamHandler`` class now has a ``terminator`` attribute, default
Vinay Sajip9a6b4002010-12-14 19:40:21 +00002571 value ``'\n'``, which is used as the terminator when writing a formatted
Vinay Sajip05ed6952010-10-20 20:34:09 +00002572 record to a stream. If you don't want this newline termination, you can
2573 set the handler instance's ``terminator`` attribute to the empty string.
Georg Brandl116aa622007-08-15 14:28:22 +00002574
Vinay Sajipd31f3632010-06-29 15:31:15 +00002575.. _file-handler:
2576
Georg Brandl116aa622007-08-15 14:28:22 +00002577FileHandler
2578^^^^^^^^^^^
2579
2580The :class:`FileHandler` class, located in the core :mod:`logging` package,
2581sends logging output to a disk file. It inherits the output functionality from
2582:class:`StreamHandler`.
2583
2584
Vinay Sajipd31f3632010-06-29 15:31:15 +00002585.. class:: FileHandler(filename, mode='a', encoding=None, delay=False)
Georg Brandl116aa622007-08-15 14:28:22 +00002586
2587 Returns a new instance of the :class:`FileHandler` class. The specified file is
2588 opened and used as the stream for logging. If *mode* is not specified,
2589 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Christian Heimese7a15bb2008-01-24 16:21:45 +00002590 with that encoding. If *delay* is true, then file opening is deferred until the
2591 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002592
2593
Benjamin Petersone41251e2008-04-25 01:59:09 +00002594 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002595
Benjamin Petersone41251e2008-04-25 01:59:09 +00002596 Closes the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002597
2598
Benjamin Petersone41251e2008-04-25 01:59:09 +00002599 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002600
Benjamin Petersone41251e2008-04-25 01:59:09 +00002601 Outputs the record to the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002602
Georg Brandl1eb40bc2010-12-03 15:30:09 +00002603
Vinay Sajipd31f3632010-06-29 15:31:15 +00002604.. _null-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002605
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002606NullHandler
2607^^^^^^^^^^^
2608
2609.. versionadded:: 3.1
2610
2611The :class:`NullHandler` class, located in the core :mod:`logging` package,
Vinay Sajip9a6b4002010-12-14 19:40:21 +00002612does not do any formatting or output. It is essentially a 'no-op' handler
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002613for use by library developers.
2614
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002615.. class:: NullHandler()
2616
2617 Returns a new instance of the :class:`NullHandler` class.
2618
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002619 .. method:: emit(record)
2620
2621 This method does nothing.
2622
Vinay Sajip76ca3b42010-09-27 13:53:47 +00002623 .. method:: handle(record)
2624
2625 This method does nothing.
2626
2627 .. method:: createLock()
2628
Senthil Kumaran46a48be2010-10-15 13:10:10 +00002629 This method returns ``None`` for the lock, since there is no
Vinay Sajip76ca3b42010-09-27 13:53:47 +00002630 underlying I/O to which access needs to be serialized.
2631
2632
Vinay Sajip26a2d5e2009-01-10 13:37:26 +00002633See :ref:`library-config` for more information on how to use
2634:class:`NullHandler`.
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00002635
Vinay Sajipd31f3632010-06-29 15:31:15 +00002636.. _watched-file-handler:
2637
Georg Brandl116aa622007-08-15 14:28:22 +00002638WatchedFileHandler
2639^^^^^^^^^^^^^^^^^^
2640
Benjamin Peterson058e31e2009-01-16 03:54:08 +00002641.. currentmodule:: logging.handlers
Vinay Sajipaa672eb2009-01-02 18:53:45 +00002642
Georg Brandl116aa622007-08-15 14:28:22 +00002643The :class:`WatchedFileHandler` class, located in the :mod:`logging.handlers`
2644module, is a :class:`FileHandler` which watches the file it is logging to. If
2645the file changes, it is closed and reopened using the file name.
2646
2647A file change can happen because of usage of programs such as *newsyslog* and
2648*logrotate* which perform log file rotation. This handler, intended for use
2649under Unix/Linux, watches the file to see if it has changed since the last emit.
2650(A file is deemed to have changed if its device or inode have changed.) If the
2651file has changed, the old file stream is closed, and the file opened to get a
2652new stream.
2653
2654This handler is not appropriate for use under Windows, because under Windows
2655open log files cannot be moved or renamed - logging opens the files with
2656exclusive locks - and so there is no need for such a handler. Furthermore,
2657*ST_INO* is not supported under Windows; :func:`stat` always returns zero for
2658this value.
2659
2660
Christian Heimese7a15bb2008-01-24 16:21:45 +00002661.. class:: WatchedFileHandler(filename[,mode[, encoding[, delay]]])
Georg Brandl116aa622007-08-15 14:28:22 +00002662
2663 Returns a new instance of the :class:`WatchedFileHandler` class. The specified
2664 file is opened and used as the stream for logging. If *mode* is not specified,
2665 :const:`'a'` is used. If *encoding* is not *None*, it is used to open the file
Christian Heimese7a15bb2008-01-24 16:21:45 +00002666 with that encoding. If *delay* is true, then file opening is deferred until the
2667 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002668
2669
Benjamin Petersone41251e2008-04-25 01:59:09 +00002670 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002671
Benjamin Petersone41251e2008-04-25 01:59:09 +00002672 Outputs the record to the file, but first checks to see if the file has
2673 changed. If it has, the existing stream is flushed and closed and the
2674 file opened again, before outputting the record to the file.
Georg Brandl116aa622007-08-15 14:28:22 +00002675
Vinay Sajipd31f3632010-06-29 15:31:15 +00002676.. _rotating-file-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002677
2678RotatingFileHandler
2679^^^^^^^^^^^^^^^^^^^
2680
2681The :class:`RotatingFileHandler` class, located in the :mod:`logging.handlers`
2682module, supports rotation of disk log files.
2683
2684
Georg Brandlcd7f32b2009-06-08 09:13:45 +00002685.. class:: RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0)
Georg Brandl116aa622007-08-15 14:28:22 +00002686
2687 Returns a new instance of the :class:`RotatingFileHandler` class. The specified
2688 file is opened and used as the stream for logging. If *mode* is not specified,
Christian Heimese7a15bb2008-01-24 16:21:45 +00002689 ``'a'`` is used. If *encoding* is not *None*, it is used to open the file
2690 with that encoding. If *delay* is true, then file opening is deferred until the
2691 first call to :meth:`emit`. By default, the file grows indefinitely.
Georg Brandl116aa622007-08-15 14:28:22 +00002692
2693 You can use the *maxBytes* and *backupCount* values to allow the file to
2694 :dfn:`rollover` at a predetermined size. When the size is about to be exceeded,
2695 the file is closed and a new file is silently opened for output. Rollover occurs
2696 whenever the current log file is nearly *maxBytes* in length; if *maxBytes* is
2697 zero, rollover never occurs. If *backupCount* is non-zero, the system will save
Vinay Sajip9a6b4002010-12-14 19:40:21 +00002698 old log files by appending the extensions '.1', '.2' etc., to the filename. For
Georg Brandl116aa622007-08-15 14:28:22 +00002699 example, with a *backupCount* of 5 and a base file name of :file:`app.log`, you
2700 would get :file:`app.log`, :file:`app.log.1`, :file:`app.log.2`, up to
2701 :file:`app.log.5`. The file being written to is always :file:`app.log`. When
2702 this file is filled, it is closed and renamed to :file:`app.log.1`, and if files
2703 :file:`app.log.1`, :file:`app.log.2`, etc. exist, then they are renamed to
2704 :file:`app.log.2`, :file:`app.log.3` etc. respectively.
2705
2706
Benjamin Petersone41251e2008-04-25 01:59:09 +00002707 .. method:: doRollover()
Georg Brandl116aa622007-08-15 14:28:22 +00002708
Benjamin Petersone41251e2008-04-25 01:59:09 +00002709 Does a rollover, as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002710
2711
Benjamin Petersone41251e2008-04-25 01:59:09 +00002712 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002713
Benjamin Petersone41251e2008-04-25 01:59:09 +00002714 Outputs the record to the file, catering for rollover as described
2715 previously.
Georg Brandl116aa622007-08-15 14:28:22 +00002716
Vinay Sajipd31f3632010-06-29 15:31:15 +00002717.. _timed-rotating-file-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00002718
2719TimedRotatingFileHandler
2720^^^^^^^^^^^^^^^^^^^^^^^^
2721
2722The :class:`TimedRotatingFileHandler` class, located in the
2723:mod:`logging.handlers` module, supports rotation of disk log files at certain
2724timed intervals.
2725
2726
Vinay Sajipd31f3632010-06-29 15:31:15 +00002727.. class:: TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False)
Georg Brandl116aa622007-08-15 14:28:22 +00002728
2729 Returns a new instance of the :class:`TimedRotatingFileHandler` class. The
2730 specified file is opened and used as the stream for logging. On rotating it also
2731 sets the filename suffix. Rotating happens based on the product of *when* and
2732 *interval*.
2733
2734 You can use the *when* to specify the type of *interval*. The list of possible
Georg Brandl0c77a822008-06-10 16:37:50 +00002735 values is below. Note that they are not case sensitive.
Georg Brandl116aa622007-08-15 14:28:22 +00002736
Christian Heimesb558a2e2008-03-02 22:46:37 +00002737 +----------------+-----------------------+
2738 | Value | Type of interval |
2739 +================+=======================+
2740 | ``'S'`` | Seconds |
2741 +----------------+-----------------------+
2742 | ``'M'`` | Minutes |
2743 +----------------+-----------------------+
2744 | ``'H'`` | Hours |
2745 +----------------+-----------------------+
2746 | ``'D'`` | Days |
2747 +----------------+-----------------------+
2748 | ``'W'`` | Week day (0=Monday) |
2749 +----------------+-----------------------+
2750 | ``'midnight'`` | Roll over at midnight |
2751 +----------------+-----------------------+
Georg Brandl116aa622007-08-15 14:28:22 +00002752
Christian Heimesb558a2e2008-03-02 22:46:37 +00002753 The system will save old log files by appending extensions to the filename.
2754 The extensions are date-and-time based, using the strftime format
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00002755 ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on the
Georg Brandl3dbca812008-07-23 16:10:53 +00002756 rollover interval.
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00002757
2758 When computing the next rollover time for the first time (when the handler
2759 is created), the last modification time of an existing log file, or else
2760 the current time, is used to compute when the next rotation will occur.
2761
Georg Brandl0c77a822008-06-10 16:37:50 +00002762 If the *utc* argument is true, times in UTC will be used; otherwise
2763 local time is used.
2764
2765 If *backupCount* is nonzero, at most *backupCount* files
Benjamin Petersonad9d48d2008-04-02 21:49:44 +00002766 will be kept, and if more would be created when rollover occurs, the oldest
2767 one is deleted. The deletion logic uses the interval to determine which
2768 files to delete, so changing the interval may leave old files lying around.
Georg Brandl116aa622007-08-15 14:28:22 +00002769
Vinay Sajipd31f3632010-06-29 15:31:15 +00002770 If *delay* is true, then file opening is deferred until the first call to
2771 :meth:`emit`.
2772
Georg Brandl116aa622007-08-15 14:28:22 +00002773
Benjamin Petersone41251e2008-04-25 01:59:09 +00002774 .. method:: doRollover()
Georg Brandl116aa622007-08-15 14:28:22 +00002775
Benjamin Petersone41251e2008-04-25 01:59:09 +00002776 Does a rollover, as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002777
2778
Benjamin Petersone41251e2008-04-25 01:59:09 +00002779 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002780
Benjamin Petersone41251e2008-04-25 01:59:09 +00002781 Outputs the record to the file, catering for rollover as described above.
Georg Brandl116aa622007-08-15 14:28:22 +00002782
2783
Vinay Sajipd31f3632010-06-29 15:31:15 +00002784.. _socket-handler:
2785
Georg Brandl116aa622007-08-15 14:28:22 +00002786SocketHandler
2787^^^^^^^^^^^^^
2788
2789The :class:`SocketHandler` class, located in the :mod:`logging.handlers` module,
2790sends logging output to a network socket. The base class uses a TCP socket.
2791
2792
2793.. class:: SocketHandler(host, port)
2794
2795 Returns a new instance of the :class:`SocketHandler` class intended to
2796 communicate with a remote machine whose address is given by *host* and *port*.
2797
2798
Benjamin Petersone41251e2008-04-25 01:59:09 +00002799 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002800
Benjamin Petersone41251e2008-04-25 01:59:09 +00002801 Closes the socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002802
2803
Benjamin Petersone41251e2008-04-25 01:59:09 +00002804 .. method:: emit()
Georg Brandl116aa622007-08-15 14:28:22 +00002805
Benjamin Petersone41251e2008-04-25 01:59:09 +00002806 Pickles the record's attribute dictionary and writes it to the socket in
2807 binary format. If there is an error with the socket, silently drops the
2808 packet. If the connection was previously lost, re-establishes the
2809 connection. To unpickle the record at the receiving end into a
2810 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl116aa622007-08-15 14:28:22 +00002811
2812
Benjamin Petersone41251e2008-04-25 01:59:09 +00002813 .. method:: handleError()
Georg Brandl116aa622007-08-15 14:28:22 +00002814
Benjamin Petersone41251e2008-04-25 01:59:09 +00002815 Handles an error which has occurred during :meth:`emit`. The most likely
2816 cause is a lost connection. Closes the socket so that we can retry on the
2817 next event.
Georg Brandl116aa622007-08-15 14:28:22 +00002818
2819
Benjamin Petersone41251e2008-04-25 01:59:09 +00002820 .. method:: makeSocket()
Georg Brandl116aa622007-08-15 14:28:22 +00002821
Benjamin Petersone41251e2008-04-25 01:59:09 +00002822 This is a factory method which allows subclasses to define the precise
2823 type of socket they want. The default implementation creates a TCP socket
2824 (:const:`socket.SOCK_STREAM`).
Georg Brandl116aa622007-08-15 14:28:22 +00002825
2826
Benjamin Petersone41251e2008-04-25 01:59:09 +00002827 .. method:: makePickle(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002828
Benjamin Petersone41251e2008-04-25 01:59:09 +00002829 Pickles the record's attribute dictionary in binary format with a length
2830 prefix, and returns it ready for transmission across the socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002831
Vinay Sajipd31f3632010-06-29 15:31:15 +00002832 Note that pickles aren't completely secure. If you are concerned about
2833 security, you may want to override this method to implement a more secure
2834 mechanism. For example, you can sign pickles using HMAC and then verify
2835 them on the receiving end, or alternatively you can disable unpickling of
2836 global objects on the receiving end.
Georg Brandl116aa622007-08-15 14:28:22 +00002837
Benjamin Petersone41251e2008-04-25 01:59:09 +00002838 .. method:: send(packet)
Georg Brandl116aa622007-08-15 14:28:22 +00002839
Benjamin Petersone41251e2008-04-25 01:59:09 +00002840 Send a pickled string *packet* to the socket. This function allows for
2841 partial sends which can happen when the network is busy.
Georg Brandl116aa622007-08-15 14:28:22 +00002842
2843
Vinay Sajipd31f3632010-06-29 15:31:15 +00002844.. _datagram-handler:
2845
Georg Brandl116aa622007-08-15 14:28:22 +00002846DatagramHandler
2847^^^^^^^^^^^^^^^
2848
2849The :class:`DatagramHandler` class, located in the :mod:`logging.handlers`
2850module, inherits from :class:`SocketHandler` to support sending logging messages
2851over UDP sockets.
2852
2853
2854.. class:: DatagramHandler(host, port)
2855
2856 Returns a new instance of the :class:`DatagramHandler` class intended to
2857 communicate with a remote machine whose address is given by *host* and *port*.
2858
2859
Benjamin Petersone41251e2008-04-25 01:59:09 +00002860 .. method:: emit()
Georg Brandl116aa622007-08-15 14:28:22 +00002861
Benjamin Petersone41251e2008-04-25 01:59:09 +00002862 Pickles the record's attribute dictionary and writes it to the socket in
2863 binary format. If there is an error with the socket, silently drops the
2864 packet. To unpickle the record at the receiving end into a
2865 :class:`LogRecord`, use the :func:`makeLogRecord` function.
Georg Brandl116aa622007-08-15 14:28:22 +00002866
2867
Benjamin Petersone41251e2008-04-25 01:59:09 +00002868 .. method:: makeSocket()
Georg Brandl116aa622007-08-15 14:28:22 +00002869
Benjamin Petersone41251e2008-04-25 01:59:09 +00002870 The factory method of :class:`SocketHandler` is here overridden to create
2871 a UDP socket (:const:`socket.SOCK_DGRAM`).
Georg Brandl116aa622007-08-15 14:28:22 +00002872
2873
Benjamin Petersone41251e2008-04-25 01:59:09 +00002874 .. method:: send(s)
Georg Brandl116aa622007-08-15 14:28:22 +00002875
Benjamin Petersone41251e2008-04-25 01:59:09 +00002876 Send a pickled string to a socket.
Georg Brandl116aa622007-08-15 14:28:22 +00002877
2878
Vinay Sajipd31f3632010-06-29 15:31:15 +00002879.. _syslog-handler:
2880
Georg Brandl116aa622007-08-15 14:28:22 +00002881SysLogHandler
2882^^^^^^^^^^^^^
2883
2884The :class:`SysLogHandler` class, located in the :mod:`logging.handlers` module,
2885supports sending logging messages to a remote or local Unix syslog.
2886
2887
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002888.. class:: SysLogHandler(address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER, socktype=socket.SOCK_DGRAM)
Georg Brandl116aa622007-08-15 14:28:22 +00002889
2890 Returns a new instance of the :class:`SysLogHandler` class intended to
2891 communicate with a remote Unix machine whose address is given by *address* in
2892 the form of a ``(host, port)`` tuple. If *address* is not specified,
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002893 ``('localhost', 514)`` is used. The address is used to open a socket. An
Georg Brandl116aa622007-08-15 14:28:22 +00002894 alternative to providing a ``(host, port)`` tuple is providing an address as a
Vinay Sajip9a6b4002010-12-14 19:40:21 +00002895 string, for example '/dev/log'. In this case, a Unix domain socket is used to
Georg Brandl116aa622007-08-15 14:28:22 +00002896 send the message to the syslog. If *facility* is not specified,
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002897 :const:`LOG_USER` is used. The type of socket opened depends on the
2898 *socktype* argument, which defaults to :const:`socket.SOCK_DGRAM` and thus
2899 opens a UDP socket. To open a TCP socket (for use with the newer syslog
2900 daemons such as rsyslog), specify a value of :const:`socket.SOCK_STREAM`.
2901
Vinay Sajip972412d2010-09-23 20:31:24 +00002902 Note that if your server is not listening on UDP port 514,
2903 :class:`SysLogHandler` may appear not to work. In that case, check what
2904 address you should be using for a domain socket - it's system dependent.
Vinay Sajip9a6b4002010-12-14 19:40:21 +00002905 For example, on Linux it's usually '/dev/log' but on OS/X it's
2906 '/var/run/syslog'. You'll need to check your platform and use the
Vinay Sajip972412d2010-09-23 20:31:24 +00002907 appropriate address (you may need to do this check at runtime if your
2908 application needs to run on several platforms). On Windows, you pretty
2909 much have to use the UDP option.
2910
Vinay Sajipcbabd7e2009-10-10 20:32:36 +00002911 .. versionchanged:: 3.2
2912 *socktype* was added.
Georg Brandl116aa622007-08-15 14:28:22 +00002913
2914
Benjamin Petersone41251e2008-04-25 01:59:09 +00002915 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00002916
Benjamin Petersone41251e2008-04-25 01:59:09 +00002917 Closes the socket to the remote host.
Georg Brandl116aa622007-08-15 14:28:22 +00002918
2919
Benjamin Petersone41251e2008-04-25 01:59:09 +00002920 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00002921
Benjamin Petersone41251e2008-04-25 01:59:09 +00002922 The record is formatted, and then sent to the syslog server. If exception
2923 information is present, it is *not* sent to the server.
Georg Brandl116aa622007-08-15 14:28:22 +00002924
2925
Benjamin Petersone41251e2008-04-25 01:59:09 +00002926 .. method:: encodePriority(facility, priority)
Georg Brandl116aa622007-08-15 14:28:22 +00002927
Benjamin Petersone41251e2008-04-25 01:59:09 +00002928 Encodes the facility and priority into an integer. You can pass in strings
2929 or integers - if strings are passed, internal mapping dictionaries are
2930 used to convert them to integers.
Georg Brandl116aa622007-08-15 14:28:22 +00002931
Benjamin Peterson22005fc2010-04-11 16:25:06 +00002932 The symbolic ``LOG_`` values are defined in :class:`SysLogHandler` and
2933 mirror the values defined in the ``sys/syslog.h`` header file.
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002934
Georg Brandl88d7dbd2010-04-18 09:50:07 +00002935 **Priorities**
2936
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002937 +--------------------------+---------------+
2938 | Name (string) | Symbolic value|
2939 +==========================+===============+
2940 | ``alert`` | LOG_ALERT |
2941 +--------------------------+---------------+
2942 | ``crit`` or ``critical`` | LOG_CRIT |
2943 +--------------------------+---------------+
2944 | ``debug`` | LOG_DEBUG |
2945 +--------------------------+---------------+
2946 | ``emerg`` or ``panic`` | LOG_EMERG |
2947 +--------------------------+---------------+
2948 | ``err`` or ``error`` | LOG_ERR |
2949 +--------------------------+---------------+
2950 | ``info`` | LOG_INFO |
2951 +--------------------------+---------------+
2952 | ``notice`` | LOG_NOTICE |
2953 +--------------------------+---------------+
2954 | ``warn`` or ``warning`` | LOG_WARNING |
2955 +--------------------------+---------------+
2956
Georg Brandl88d7dbd2010-04-18 09:50:07 +00002957 **Facilities**
2958
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00002959 +---------------+---------------+
2960 | Name (string) | Symbolic value|
2961 +===============+===============+
2962 | ``auth`` | LOG_AUTH |
2963 +---------------+---------------+
2964 | ``authpriv`` | LOG_AUTHPRIV |
2965 +---------------+---------------+
2966 | ``cron`` | LOG_CRON |
2967 +---------------+---------------+
2968 | ``daemon`` | LOG_DAEMON |
2969 +---------------+---------------+
2970 | ``ftp`` | LOG_FTP |
2971 +---------------+---------------+
2972 | ``kern`` | LOG_KERN |
2973 +---------------+---------------+
2974 | ``lpr`` | LOG_LPR |
2975 +---------------+---------------+
2976 | ``mail`` | LOG_MAIL |
2977 +---------------+---------------+
2978 | ``news`` | LOG_NEWS |
2979 +---------------+---------------+
2980 | ``syslog`` | LOG_SYSLOG |
2981 +---------------+---------------+
2982 | ``user`` | LOG_USER |
2983 +---------------+---------------+
2984 | ``uucp`` | LOG_UUCP |
2985 +---------------+---------------+
2986 | ``local0`` | LOG_LOCAL0 |
2987 +---------------+---------------+
2988 | ``local1`` | LOG_LOCAL1 |
2989 +---------------+---------------+
2990 | ``local2`` | LOG_LOCAL2 |
2991 +---------------+---------------+
2992 | ``local3`` | LOG_LOCAL3 |
2993 +---------------+---------------+
2994 | ``local4`` | LOG_LOCAL4 |
2995 +---------------+---------------+
2996 | ``local5`` | LOG_LOCAL5 |
2997 +---------------+---------------+
2998 | ``local6`` | LOG_LOCAL6 |
2999 +---------------+---------------+
3000 | ``local7`` | LOG_LOCAL7 |
3001 +---------------+---------------+
3002
3003 .. method:: mapPriority(levelname)
3004
3005 Maps a logging level name to a syslog priority name.
3006 You may need to override this if you are using custom levels, or
3007 if the default algorithm is not suitable for your needs. The
3008 default algorithm maps ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and
3009 ``CRITICAL`` to the equivalent syslog names, and all other level
Vinay Sajip9a6b4002010-12-14 19:40:21 +00003010 names to 'warning'.
Benjamin Peterson08bf91c2010-04-11 16:12:57 +00003011
3012.. _nt-eventlog-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00003013
3014NTEventLogHandler
3015^^^^^^^^^^^^^^^^^
3016
3017The :class:`NTEventLogHandler` class, located in the :mod:`logging.handlers`
3018module, supports sending logging messages to a local Windows NT, Windows 2000 or
3019Windows XP event log. Before you can use it, you need Mark Hammond's Win32
3020extensions for Python installed.
3021
3022
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003023.. class:: NTEventLogHandler(appname, dllname=None, logtype='Application')
Georg Brandl116aa622007-08-15 14:28:22 +00003024
3025 Returns a new instance of the :class:`NTEventLogHandler` class. The *appname* is
3026 used to define the application name as it appears in the event log. An
3027 appropriate registry entry is created using this name. The *dllname* should give
3028 the fully qualified pathname of a .dll or .exe which contains message
3029 definitions to hold in the log (if not specified, ``'win32service.pyd'`` is used
3030 - this is installed with the Win32 extensions and contains some basic
3031 placeholder message definitions. Note that use of these placeholders will make
3032 your event logs big, as the entire message source is held in the log. If you
3033 want slimmer logs, you have to pass in the name of your own .dll or .exe which
3034 contains the message definitions you want to use in the event log). The
3035 *logtype* is one of ``'Application'``, ``'System'`` or ``'Security'``, and
3036 defaults to ``'Application'``.
3037
3038
Benjamin Petersone41251e2008-04-25 01:59:09 +00003039 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00003040
Benjamin Petersone41251e2008-04-25 01:59:09 +00003041 At this point, you can remove the application name from the registry as a
3042 source of event log entries. However, if you do this, you will not be able
3043 to see the events as you intended in the Event Log Viewer - it needs to be
3044 able to access the registry to get the .dll name. The current version does
Benjamin Peterson3e4f0552008-09-02 00:31:15 +00003045 not do this.
Georg Brandl116aa622007-08-15 14:28:22 +00003046
3047
Benjamin Petersone41251e2008-04-25 01:59:09 +00003048 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003049
Benjamin Petersone41251e2008-04-25 01:59:09 +00003050 Determines the message ID, event category and event type, and then logs
3051 the message in the NT event log.
Georg Brandl116aa622007-08-15 14:28:22 +00003052
3053
Benjamin Petersone41251e2008-04-25 01:59:09 +00003054 .. method:: getEventCategory(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003055
Benjamin Petersone41251e2008-04-25 01:59:09 +00003056 Returns the event category for the record. Override this if you want to
3057 specify your own categories. This version returns 0.
Georg Brandl116aa622007-08-15 14:28:22 +00003058
3059
Benjamin Petersone41251e2008-04-25 01:59:09 +00003060 .. method:: getEventType(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003061
Benjamin Petersone41251e2008-04-25 01:59:09 +00003062 Returns the event type for the record. Override this if you want to
3063 specify your own types. This version does a mapping using the handler's
3064 typemap attribute, which is set up in :meth:`__init__` to a dictionary
3065 which contains mappings for :const:`DEBUG`, :const:`INFO`,
3066 :const:`WARNING`, :const:`ERROR` and :const:`CRITICAL`. If you are using
3067 your own levels, you will either need to override this method or place a
3068 suitable dictionary in the handler's *typemap* attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00003069
3070
Benjamin Petersone41251e2008-04-25 01:59:09 +00003071 .. method:: getMessageID(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003072
Benjamin Petersone41251e2008-04-25 01:59:09 +00003073 Returns the message ID for the record. If you are using your own messages,
3074 you could do this by having the *msg* passed to the logger being an ID
3075 rather than a format string. Then, in here, you could use a dictionary
3076 lookup to get the message ID. This version returns 1, which is the base
3077 message ID in :file:`win32service.pyd`.
Georg Brandl116aa622007-08-15 14:28:22 +00003078
Vinay Sajipd31f3632010-06-29 15:31:15 +00003079.. _smtp-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00003080
3081SMTPHandler
3082^^^^^^^^^^^
3083
3084The :class:`SMTPHandler` class, located in the :mod:`logging.handlers` module,
3085supports sending logging messages to an email address via SMTP.
3086
3087
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003088.. class:: SMTPHandler(mailhost, fromaddr, toaddrs, subject, credentials=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003089
3090 Returns a new instance of the :class:`SMTPHandler` class. The instance is
3091 initialized with the from and to addresses and subject line of the email. The
3092 *toaddrs* should be a list of strings. To specify a non-standard SMTP port, use
3093 the (host, port) tuple format for the *mailhost* argument. If you use a string,
3094 the standard SMTP port is used. If your SMTP server requires authentication, you
3095 can specify a (username, password) tuple for the *credentials* argument.
3096
Georg Brandl116aa622007-08-15 14:28:22 +00003097
Benjamin Petersone41251e2008-04-25 01:59:09 +00003098 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003099
Benjamin Petersone41251e2008-04-25 01:59:09 +00003100 Formats the record and sends it to the specified addressees.
Georg Brandl116aa622007-08-15 14:28:22 +00003101
3102
Benjamin Petersone41251e2008-04-25 01:59:09 +00003103 .. method:: getSubject(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003104
Benjamin Petersone41251e2008-04-25 01:59:09 +00003105 If you want to specify a subject line which is record-dependent, override
3106 this method.
Georg Brandl116aa622007-08-15 14:28:22 +00003107
Vinay Sajipd31f3632010-06-29 15:31:15 +00003108.. _memory-handler:
Georg Brandl116aa622007-08-15 14:28:22 +00003109
3110MemoryHandler
3111^^^^^^^^^^^^^
3112
3113The :class:`MemoryHandler` class, located in the :mod:`logging.handlers` module,
3114supports buffering of logging records in memory, periodically flushing them to a
3115:dfn:`target` handler. Flushing occurs whenever the buffer is full, or when an
3116event of a certain severity or greater is seen.
3117
3118:class:`MemoryHandler` is a subclass of the more general
3119:class:`BufferingHandler`, which is an abstract class. This buffers logging
3120records in memory. Whenever each record is added to the buffer, a check is made
3121by calling :meth:`shouldFlush` to see if the buffer should be flushed. If it
3122should, then :meth:`flush` is expected to do the needful.
3123
3124
3125.. class:: BufferingHandler(capacity)
3126
3127 Initializes the handler with a buffer of the specified capacity.
3128
3129
Benjamin Petersone41251e2008-04-25 01:59:09 +00003130 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003131
Benjamin Petersone41251e2008-04-25 01:59:09 +00003132 Appends the record to the buffer. If :meth:`shouldFlush` returns true,
3133 calls :meth:`flush` to process the buffer.
Georg Brandl116aa622007-08-15 14:28:22 +00003134
3135
Benjamin Petersone41251e2008-04-25 01:59:09 +00003136 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00003137
Benjamin Petersone41251e2008-04-25 01:59:09 +00003138 You can override this to implement custom flushing behavior. This version
3139 just zaps the buffer to empty.
Georg Brandl116aa622007-08-15 14:28:22 +00003140
3141
Benjamin Petersone41251e2008-04-25 01:59:09 +00003142 .. method:: shouldFlush(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003143
Benjamin Petersone41251e2008-04-25 01:59:09 +00003144 Returns true if the buffer is up to capacity. This method can be
3145 overridden to implement custom flushing strategies.
Georg Brandl116aa622007-08-15 14:28:22 +00003146
3147
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003148.. class:: MemoryHandler(capacity, flushLevel=ERROR, target=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003149
3150 Returns a new instance of the :class:`MemoryHandler` class. The instance is
3151 initialized with a buffer size of *capacity*. If *flushLevel* is not specified,
3152 :const:`ERROR` is used. If no *target* is specified, the target will need to be
3153 set using :meth:`setTarget` before this handler does anything useful.
3154
3155
Benjamin Petersone41251e2008-04-25 01:59:09 +00003156 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +00003157
Benjamin Petersone41251e2008-04-25 01:59:09 +00003158 Calls :meth:`flush`, sets the target to :const:`None` and clears the
3159 buffer.
Georg Brandl116aa622007-08-15 14:28:22 +00003160
3161
Benjamin Petersone41251e2008-04-25 01:59:09 +00003162 .. method:: flush()
Georg Brandl116aa622007-08-15 14:28:22 +00003163
Benjamin Petersone41251e2008-04-25 01:59:09 +00003164 For a :class:`MemoryHandler`, flushing means just sending the buffered
Vinay Sajipc84f0162010-09-21 11:25:39 +00003165 records to the target, if there is one. The buffer is also cleared when
3166 this happens. Override if you want different behavior.
Georg Brandl116aa622007-08-15 14:28:22 +00003167
3168
Benjamin Petersone41251e2008-04-25 01:59:09 +00003169 .. method:: setTarget(target)
Georg Brandl116aa622007-08-15 14:28:22 +00003170
Benjamin Petersone41251e2008-04-25 01:59:09 +00003171 Sets the target handler for this handler.
Georg Brandl116aa622007-08-15 14:28:22 +00003172
3173
Benjamin Petersone41251e2008-04-25 01:59:09 +00003174 .. method:: shouldFlush(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003175
Benjamin Petersone41251e2008-04-25 01:59:09 +00003176 Checks for buffer full or a record at the *flushLevel* or higher.
Georg Brandl116aa622007-08-15 14:28:22 +00003177
3178
Vinay Sajipd31f3632010-06-29 15:31:15 +00003179.. _http-handler:
3180
Georg Brandl116aa622007-08-15 14:28:22 +00003181HTTPHandler
3182^^^^^^^^^^^
3183
3184The :class:`HTTPHandler` class, located in the :mod:`logging.handlers` module,
3185supports sending logging messages to a Web server, using either ``GET`` or
3186``POST`` semantics.
3187
3188
Vinay Sajip1b5646a2010-09-13 20:37:50 +00003189.. class:: HTTPHandler(host, url, method='GET', secure=False, credentials=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003190
Vinay Sajip1b5646a2010-09-13 20:37:50 +00003191 Returns a new instance of the :class:`HTTPHandler` class. The *host* can be
3192 of the form ``host:port``, should you need to use a specific port number.
3193 If no *method* is specified, ``GET`` is used. If *secure* is True, an HTTPS
3194 connection will be used. If *credentials* is specified, it should be a
3195 2-tuple consisting of userid and password, which will be placed in an HTTP
3196 'Authorization' header using Basic authentication. If you specify
3197 credentials, you should also specify secure=True so that your userid and
3198 password are not passed in cleartext across the wire.
Georg Brandl116aa622007-08-15 14:28:22 +00003199
3200
Benjamin Petersone41251e2008-04-25 01:59:09 +00003201 .. method:: emit(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003202
Senthil Kumaranf0769e82010-08-09 19:53:52 +00003203 Sends the record to the Web server as a percent-encoded dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +00003204
3205
Vinay Sajip121a1c42010-09-08 10:46:15 +00003206.. _queue-handler:
3207
3208
3209QueueHandler
3210^^^^^^^^^^^^
3211
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003212.. versionadded:: 3.2
3213
Vinay Sajip121a1c42010-09-08 10:46:15 +00003214The :class:`QueueHandler` class, located in the :mod:`logging.handlers` module,
3215supports sending logging messages to a queue, such as those implemented in the
3216:mod:`queue` or :mod:`multiprocessing` modules.
3217
Vinay Sajip0637d492010-09-23 08:15:54 +00003218Along with the :class:`QueueListener` class, :class:`QueueHandler` can be used
3219to let handlers do their work on a separate thread from the one which does the
3220logging. This is important in Web applications and also other service
3221applications where threads servicing clients need to respond as quickly as
3222possible, while any potentially slow operations (such as sending an email via
3223:class:`SMTPHandler`) are done on a separate thread.
Vinay Sajip121a1c42010-09-08 10:46:15 +00003224
3225.. class:: QueueHandler(queue)
3226
3227 Returns a new instance of the :class:`QueueHandler` class. The instance is
Vinay Sajip63891ed2010-09-13 20:02:39 +00003228 initialized with the queue to send messages to. The queue can be any queue-
Vinay Sajip0637d492010-09-23 08:15:54 +00003229 like object; it's used as-is by the :meth:`enqueue` method, which needs
Vinay Sajip63891ed2010-09-13 20:02:39 +00003230 to know how to send messages to it.
Vinay Sajip121a1c42010-09-08 10:46:15 +00003231
3232
3233 .. method:: emit(record)
3234
Vinay Sajip0258ce82010-09-22 20:34:53 +00003235 Enqueues the result of preparing the LogRecord.
3236
3237 .. method:: prepare(record)
3238
3239 Prepares a record for queuing. The object returned by this
3240 method is enqueued.
3241
3242 The base implementation formats the record to merge the message
3243 and arguments, and removes unpickleable items from the record
3244 in-place.
3245
3246 You might want to override this method if you want to convert
3247 the record to a dict or JSON string, or send a modified copy
3248 of the record while leaving the original intact.
Vinay Sajip121a1c42010-09-08 10:46:15 +00003249
3250 .. method:: enqueue(record)
3251
3252 Enqueues the record on the queue using ``put_nowait()``; you may
3253 want to override this if you want to use blocking behaviour, or a
3254 timeout, or a customised queue implementation.
3255
3256
Vinay Sajip121a1c42010-09-08 10:46:15 +00003257
Vinay Sajip0637d492010-09-23 08:15:54 +00003258.. queue-listener:
3259
3260QueueListener
3261^^^^^^^^^^^^^
3262
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003263.. versionadded:: 3.2
3264
Vinay Sajip0637d492010-09-23 08:15:54 +00003265The :class:`QueueListener` class, located in the :mod:`logging.handlers`
3266module, supports receiving logging messages from a queue, such as those
3267implemented in the :mod:`queue` or :mod:`multiprocessing` modules. The
3268messages are received from a queue in an internal thread and passed, on
Vinay Sajip7292b882010-12-13 18:43:57 +00003269the same thread, to one or more handlers for processing. While
3270:class:`QueueListener` is not itself a handler, it is documented here
3271because it works hand-in-hand with :class:`QueueHandler`.
Vinay Sajip0637d492010-09-23 08:15:54 +00003272
3273Along with the :class:`QueueHandler` class, :class:`QueueListener` can be used
3274to let handlers do their work on a separate thread from the one which does the
3275logging. This is important in Web applications and also other service
3276applications where threads servicing clients need to respond as quickly as
3277possible, while any potentially slow operations (such as sending an email via
3278:class:`SMTPHandler`) are done on a separate thread.
3279
3280.. class:: QueueListener(queue, *handlers)
3281
3282 Returns a new instance of the :class:`QueueListener` class. The instance is
3283 initialized with the queue to send messages to and a list of handlers which
3284 will handle entries placed on the queue. The queue can be any queue-
3285 like object; it's passed as-is to the :meth:`dequeue` method, which needs
3286 to know how to get messages from it.
3287
3288 .. method:: dequeue(block)
3289
3290 Dequeues a record and return it, optionally blocking.
3291
3292 The base implementation uses ``get()``. You may want to override this
3293 method if you want to use timeouts or work with custom queue
3294 implementations.
3295
3296 .. method:: prepare(record)
3297
3298 Prepare a record for handling.
3299
3300 This implementation just returns the passed-in record. You may want to
3301 override this method if you need to do any custom marshalling or
3302 manipulation of the record before passing it to the handlers.
3303
3304 .. method:: handle(record)
3305
3306 Handle a record.
3307
3308 This just loops through the handlers offering them the record
3309 to handle. The actual object passed to the handlers is that which
3310 is returned from :meth:`prepare`.
3311
3312 .. method:: start()
3313
3314 Starts the listener.
3315
3316 This starts up a background thread to monitor the queue for
3317 LogRecords to process.
3318
3319 .. method:: stop()
3320
3321 Stops the listener.
3322
3323 This asks the thread to terminate, and then waits for it to do so.
3324 Note that if you don't call this before your application exits, there
3325 may be some records still left on the queue, which won't be processed.
3326
Vinay Sajip0637d492010-09-23 08:15:54 +00003327
Vinay Sajip63891ed2010-09-13 20:02:39 +00003328.. _zeromq-handlers:
3329
Vinay Sajip0637d492010-09-23 08:15:54 +00003330Subclassing QueueHandler
3331^^^^^^^^^^^^^^^^^^^^^^^^
3332
Vinay Sajip63891ed2010-09-13 20:02:39 +00003333You can use a :class:`QueueHandler` subclass to send messages to other kinds
Vinay Sajip9a6b4002010-12-14 19:40:21 +00003334of queues, for example a ZeroMQ 'publish' socket. In the example below,the
Vinay Sajip63891ed2010-09-13 20:02:39 +00003335socket is created separately and passed to the handler (as its 'queue')::
3336
3337 import zmq # using pyzmq, the Python binding for ZeroMQ
3338 import json # for serializing records portably
3339
3340 ctx = zmq.Context()
3341 sock = zmq.Socket(ctx, zmq.PUB) # or zmq.PUSH, or other suitable value
3342 sock.bind('tcp://*:5556') # or wherever
3343
3344 class ZeroMQSocketHandler(QueueHandler):
3345 def enqueue(self, record):
3346 data = json.dumps(record.__dict__)
3347 self.queue.send(data)
3348
Vinay Sajip0055c422010-09-14 09:42:39 +00003349 handler = ZeroMQSocketHandler(sock)
3350
3351
Vinay Sajip63891ed2010-09-13 20:02:39 +00003352Of course there are other ways of organizing this, for example passing in the
3353data needed by the handler to create the socket::
3354
3355 class ZeroMQSocketHandler(QueueHandler):
3356 def __init__(self, uri, socktype=zmq.PUB, ctx=None):
3357 self.ctx = ctx or zmq.Context()
3358 socket = zmq.Socket(self.ctx, socktype)
Vinay Sajip0637d492010-09-23 08:15:54 +00003359 socket.bind(uri)
Vinay Sajip0055c422010-09-14 09:42:39 +00003360 QueueHandler.__init__(self, socket)
Vinay Sajip63891ed2010-09-13 20:02:39 +00003361
3362 def enqueue(self, record):
3363 data = json.dumps(record.__dict__)
3364 self.queue.send(data)
3365
Vinay Sajipde726922010-09-14 06:59:24 +00003366 def close(self):
3367 self.queue.close()
Vinay Sajip121a1c42010-09-08 10:46:15 +00003368
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003369
Vinay Sajip0637d492010-09-23 08:15:54 +00003370Subclassing QueueListener
3371^^^^^^^^^^^^^^^^^^^^^^^^^
3372
3373You can also subclass :class:`QueueListener` to get messages from other kinds
Vinay Sajip9a6b4002010-12-14 19:40:21 +00003374of queues, for example a ZeroMQ 'subscribe' socket. Here's an example::
Vinay Sajip0637d492010-09-23 08:15:54 +00003375
3376 class ZeroMQSocketListener(QueueListener):
3377 def __init__(self, uri, *handlers, **kwargs):
3378 self.ctx = kwargs.get('ctx') or zmq.Context()
3379 socket = zmq.Socket(self.ctx, zmq.SUB)
3380 socket.setsockopt(zmq.SUBSCRIBE, '') # subscribe to everything
3381 socket.connect(uri)
3382
3383 def dequeue(self):
3384 msg = self.queue.recv()
3385 return logging.makeLogRecord(json.loads(msg))
3386
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003387
Christian Heimes8b0facf2007-12-04 19:30:01 +00003388.. _formatter-objects:
3389
Georg Brandl116aa622007-08-15 14:28:22 +00003390Formatter Objects
3391-----------------
3392
Benjamin Peterson75edad02009-01-01 15:05:06 +00003393.. currentmodule:: logging
3394
Vinay Sajip7292b882010-12-13 18:43:57 +00003395:class:`Formatter` objects have the following attributes and methods. They are
Georg Brandl116aa622007-08-15 14:28:22 +00003396responsible for converting a :class:`LogRecord` to (usually) a string which can
3397be interpreted by either a human or an external system. The base
3398:class:`Formatter` allows a formatting string to be specified. If none is
3399supplied, the default value of ``'%(message)s'`` is used.
3400
3401A Formatter can be initialized with a format string which makes use of knowledge
3402of the :class:`LogRecord` attributes - such as the default value mentioned above
3403making use of the fact that the user's message and arguments are pre-formatted
3404into a :class:`LogRecord`'s *message* attribute. This format string contains
Ezio Melotti0639d5a2009-12-19 23:26:38 +00003405standard Python %-style mapping keys. See section :ref:`old-string-formatting`
Georg Brandl116aa622007-08-15 14:28:22 +00003406for more information on string formatting.
3407
Vinay Sajip7292b882010-12-13 18:43:57 +00003408The useful mapping keys in a :class:`LogRecord` are given in the section on
3409:ref:`logrecord-attributes`.
Georg Brandl116aa622007-08-15 14:28:22 +00003410
Georg Brandl116aa622007-08-15 14:28:22 +00003411
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003412.. class:: Formatter(fmt=None, datefmt=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003413
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003414 Returns a new instance of the :class:`Formatter` class. The instance is
3415 initialized with a format string for the message as a whole, as well as a
3416 format string for the date/time portion of a message. If no *fmt* is
3417 specified, ``'%(message)s'`` is used. If no *datefmt* is specified, the
3418 ISO8601 date format is used.
Georg Brandl116aa622007-08-15 14:28:22 +00003419
Benjamin Petersone41251e2008-04-25 01:59:09 +00003420 .. method:: format(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003421
Benjamin Petersone41251e2008-04-25 01:59:09 +00003422 The record's attribute dictionary is used as the operand to a string
3423 formatting operation. Returns the resulting string. Before formatting the
3424 dictionary, a couple of preparatory steps are carried out. The *message*
3425 attribute of the record is computed using *msg* % *args*. If the
3426 formatting string contains ``'(asctime)'``, :meth:`formatTime` is called
3427 to format the event time. If there is exception information, it is
3428 formatted using :meth:`formatException` and appended to the message. Note
3429 that the formatted exception information is cached in attribute
3430 *exc_text*. This is useful because the exception information can be
3431 pickled and sent across the wire, but you should be careful if you have
3432 more than one :class:`Formatter` subclass which customizes the formatting
3433 of exception information. In this case, you will have to clear the cached
3434 value after a formatter has done its formatting, so that the next
3435 formatter to handle the event doesn't use the cached value but
3436 recalculates it afresh.
Georg Brandl116aa622007-08-15 14:28:22 +00003437
Vinay Sajip8593ae62010-11-14 21:33:04 +00003438 If stack information is available, it's appended after the exception
3439 information, using :meth:`formatStack` to transform it if necessary.
3440
Georg Brandl116aa622007-08-15 14:28:22 +00003441
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003442 .. method:: formatTime(record, datefmt=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003443
Benjamin Petersone41251e2008-04-25 01:59:09 +00003444 This method should be called from :meth:`format` by a formatter which
3445 wants to make use of a formatted time. This method can be overridden in
3446 formatters to provide for any specific requirement, but the basic behavior
3447 is as follows: if *datefmt* (a string) is specified, it is used with
3448 :func:`time.strftime` to format the creation time of the
3449 record. Otherwise, the ISO8601 format is used. The resulting string is
3450 returned.
Georg Brandl116aa622007-08-15 14:28:22 +00003451
3452
Benjamin Petersone41251e2008-04-25 01:59:09 +00003453 .. method:: formatException(exc_info)
Georg Brandl116aa622007-08-15 14:28:22 +00003454
Benjamin Petersone41251e2008-04-25 01:59:09 +00003455 Formats the specified exception information (a standard exception tuple as
3456 returned by :func:`sys.exc_info`) as a string. This default implementation
3457 just uses :func:`traceback.print_exception`. The resulting string is
3458 returned.
Georg Brandl116aa622007-08-15 14:28:22 +00003459
Vinay Sajip8593ae62010-11-14 21:33:04 +00003460 .. method:: formatStack(stack_info)
3461
3462 Formats the specified stack information (a string as returned by
3463 :func:`traceback.print_stack`, but with the last newline removed) as a
3464 string. This default implementation just returns the input value.
3465
Vinay Sajipd31f3632010-06-29 15:31:15 +00003466.. _filter:
Georg Brandl116aa622007-08-15 14:28:22 +00003467
3468Filter Objects
3469--------------
3470
Georg Brandl5c66bca2010-10-29 05:36:28 +00003471``Filters`` can be used by ``Handlers`` and ``Loggers`` for more sophisticated
Vinay Sajipfc082ca2010-10-19 21:13:49 +00003472filtering than is provided by levels. The base filter class only allows events
3473which are below a certain point in the logger hierarchy. For example, a filter
Vinay Sajip9a6b4002010-12-14 19:40:21 +00003474initialized with 'A.B' will allow events logged by loggers 'A.B', 'A.B.C',
3475'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 +00003476empty string, all events are passed.
Georg Brandl116aa622007-08-15 14:28:22 +00003477
3478
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003479.. class:: Filter(name='')
Georg Brandl116aa622007-08-15 14:28:22 +00003480
3481 Returns an instance of the :class:`Filter` class. If *name* is specified, it
3482 names a logger which, together with its children, will have its events allowed
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003483 through the filter. If *name* is the empty string, allows every event.
Georg Brandl116aa622007-08-15 14:28:22 +00003484
3485
Benjamin Petersone41251e2008-04-25 01:59:09 +00003486 .. method:: filter(record)
Georg Brandl116aa622007-08-15 14:28:22 +00003487
Benjamin Petersone41251e2008-04-25 01:59:09 +00003488 Is the specified record to be logged? Returns zero for no, nonzero for
3489 yes. If deemed appropriate, the record may be modified in-place by this
3490 method.
Georg Brandl116aa622007-08-15 14:28:22 +00003491
Vinay Sajip81010212010-08-19 19:17:41 +00003492Note that filters attached to handlers are consulted whenever an event is
3493emitted by the handler, whereas filters attached to loggers are consulted
3494whenever an event is logged to the handler (using :meth:`debug`, :meth:`info`,
3495etc.) This means that events which have been generated by descendant loggers
3496will not be filtered by a logger's filter setting, unless the filter has also
3497been applied to those descendant loggers.
3498
Vinay Sajip22246fd2010-10-20 11:40:02 +00003499You don't actually need to subclass ``Filter``: you can pass any instance
3500which has a ``filter`` method with the same semantics.
3501
Vinay Sajipfc082ca2010-10-19 21:13:49 +00003502.. versionchanged:: 3.2
Vinay Sajip05ed6952010-10-20 20:34:09 +00003503 You don't need to create specialized ``Filter`` classes, or use other
3504 classes with a ``filter`` method: you can use a function (or other
3505 callable) as a filter. The filtering logic will check to see if the filter
3506 object has a ``filter`` attribute: if it does, it's assumed to be a
3507 ``Filter`` and its :meth:`~Filter.filter` method is called. Otherwise, it's
3508 assumed to be a callable and called with the record as the single
3509 parameter. The returned value should conform to that returned by
3510 :meth:`~Filter.filter`.
Vinay Sajipfc082ca2010-10-19 21:13:49 +00003511
Vinay Sajipac007992010-09-17 12:45:26 +00003512Other uses for filters
3513^^^^^^^^^^^^^^^^^^^^^^
3514
3515Although filters are used primarily to filter records based on more
3516sophisticated criteria than levels, they get to see every record which is
3517processed by the handler or logger they're attached to: this can be useful if
3518you want to do things like counting how many records were processed by a
3519particular logger or handler, or adding, changing or removing attributes in
3520the LogRecord being processed. Obviously changing the LogRecord needs to be
3521done with some care, but it does allow the injection of contextual information
3522into logs (see :ref:`filters-contextual`).
3523
Vinay Sajipd31f3632010-06-29 15:31:15 +00003524.. _log-record:
Georg Brandl116aa622007-08-15 14:28:22 +00003525
3526LogRecord Objects
3527-----------------
3528
Vinay Sajip4039aff2010-09-11 10:25:28 +00003529:class:`LogRecord` instances are created automatically by the :class:`Logger`
3530every time something is logged, and can be created manually via
3531:func:`makeLogRecord` (for example, from a pickled event received over the
3532wire).
Georg Brandl116aa622007-08-15 14:28:22 +00003533
3534
Vinay Sajip7292b882010-12-13 18:43:57 +00003535.. class:: LogRecord(name, level, pathname, lineno, msg, args, exc_info, func=None, sinfo=None)
Georg Brandl116aa622007-08-15 14:28:22 +00003536
Vinay Sajip4039aff2010-09-11 10:25:28 +00003537 Contains all the information pertinent to the event being logged.
Georg Brandl116aa622007-08-15 14:28:22 +00003538
Vinay Sajip4039aff2010-09-11 10:25:28 +00003539 The primary information is passed in :attr:`msg` and :attr:`args`, which
3540 are combined using ``msg % args`` to create the :attr:`message` field of the
3541 record.
3542
Vinay Sajip7292b882010-12-13 18:43:57 +00003543 :param name: The name of the logger used to log the event represented by
3544 this LogRecord.
3545 :param level: The numeric level of the logging event (one of DEBUG, INFO etc.)
3546 :param pathname: The full pathname of the source file where the logging call
3547 was made.
3548 :param lineno: The line number in the source file where the logging call was
3549 made.
3550 :param msg: The event description message, possibly a format string with
3551 placeholders for variable data.
3552 :param args: Variable data to merge into the *msg* argument to obtain the
3553 event description.
3554 :param exc_info: An exception tuple with the current exception information,
3555 or *None* if no exception information is available.
3556 :param func: The name of the function or method from which the logging call
3557 was invoked.
3558 :param sinfo: A text string representing stack information from the base of
3559 the stack in the current thread, up to the logging call.
Vinay Sajip8593ae62010-11-14 21:33:04 +00003560
Benjamin Petersone41251e2008-04-25 01:59:09 +00003561 .. method:: getMessage()
Georg Brandl116aa622007-08-15 14:28:22 +00003562
Benjamin Petersone41251e2008-04-25 01:59:09 +00003563 Returns the message for this :class:`LogRecord` instance after merging any
Vinay Sajip4039aff2010-09-11 10:25:28 +00003564 user-supplied arguments with the message. If the user-supplied message
3565 argument to the logging call is not a string, :func:`str` is called on it to
3566 convert it to a string. This allows use of user-defined classes as
3567 messages, whose ``__str__`` method can return the actual format string to
3568 be used.
3569
Vinay Sajip61561522010-12-03 11:50:38 +00003570 .. versionchanged:: 3.2
3571 The creation of a ``LogRecord`` has been made more configurable by
3572 providing a factory which is used to create the record. The factory can be
3573 set using :func:`getLogRecordFactory` and :func:`setLogRecordFactory`
3574 (see this for the factory's signature).
3575
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003576 This functionality can be used to inject your own values into a
3577 LogRecord at creation time. You can use the following pattern::
Vinay Sajip61561522010-12-03 11:50:38 +00003578
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003579 old_factory = logging.getLogRecordFactory()
Vinay Sajip61561522010-12-03 11:50:38 +00003580
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003581 def record_factory(*args, **kwargs):
3582 record = old_factory(*args, **kwargs)
3583 record.custom_attribute = 0xdecafbad
3584 return record
Vinay Sajip61561522010-12-03 11:50:38 +00003585
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003586 logging.setLogRecordFactory(record_factory)
Vinay Sajip61561522010-12-03 11:50:38 +00003587
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003588 With this pattern, multiple factories could be chained, and as long
3589 as they don't overwrite each other's attributes or unintentionally
3590 overwrite the standard attributes listed above, there should be no
3591 surprises.
3592
Vinay Sajip61561522010-12-03 11:50:38 +00003593
Vinay Sajip7292b882010-12-13 18:43:57 +00003594.. _logrecord-attributes:
3595
3596``LogRecord`` attributes
3597^^^^^^^^^^^^^^^^^^^^^^^^
3598
3599The LogRecord has a number of attributes, most of which are derived from the
3600parameters to the constructor. (Note that the names do not always correspond
3601exactly between the LogRecord constructor parameters and the LogRecord
3602attributes.) These attributes can be used to merge data from the record into
3603the format string. The following table lists (in alphabetical order) the
3604attribute names, their meanings and the corresponding placeholder in a %-style
3605format string.
3606
3607If you are using {}-formatting (:func:`str.format`), you can use
Vinay Sajipfd94b172010-12-13 18:49:08 +00003608``{attrname}`` as the placeholder in the format string. If you are using
Vinay Sajip7292b882010-12-13 18:43:57 +00003609$-formatting (:class:`string.Template`), use the form ``${attrname}``. In
3610both cases, of course, replace ``attrname`` with the actual attribute name
3611you want to use.
3612
3613In the case of {}-formatting, you can specify formatting flags by placing them
Vinay Sajipfd94b172010-12-13 18:49:08 +00003614after the attribute name, separated from it with a colon. For example: a
3615placeholder of ``{msecs:03d}`` would format a millisecond value of ``4`` as
3616``004``. Refer to the :meth:`str.format` documentation for full details on
3617the options available to you.
Vinay Sajip7292b882010-12-13 18:43:57 +00003618
3619+----------------+-------------------------+-----------------------------------------------+
3620| Attribute name | Format | Description |
3621+================+=========================+===============================================+
3622| args | You shouldn't need to | The tuple of arguments merged into ``msg`` to |
3623| | format this yourself. | produce ``message``. |
3624+----------------+-------------------------+-----------------------------------------------+
3625| asctime | ``%(asctime)s`` | Human-readable time when the |
3626| | | :class:`LogRecord` was created. By default |
Vinay Sajip9a6b4002010-12-14 19:40:21 +00003627| | | this is of the form '2003-07-08 16:49:45,896' |
Vinay Sajip7292b882010-12-13 18:43:57 +00003628| | | (the numbers after the comma are millisecond |
3629| | | portion of the time). |
3630+----------------+-------------------------+-----------------------------------------------+
3631| created | ``%(created)f`` | Time when the :class:`LogRecord` was created |
3632| | | (as returned by :func:`time.time`). |
3633+----------------+-------------------------+-----------------------------------------------+
3634| exc_info | You shouldn't need to | Exception tuple (à la ``sys.exc_info``) or, |
3635| | format this yourself. | if no exception has occurred, *None*. |
3636+----------------+-------------------------+-----------------------------------------------+
3637| filename | ``%(filename)s`` | Filename portion of ``pathname``. |
3638+----------------+-------------------------+-----------------------------------------------+
3639| funcName | ``%(funcName)s`` | Name of function containing the logging call. |
3640+----------------+-------------------------+-----------------------------------------------+
3641| levelname | ``%(levelname)s`` | Text logging level for the message |
3642| | | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |
3643| | | ``'ERROR'``, ``'CRITICAL'``). |
3644+----------------+-------------------------+-----------------------------------------------+
3645| levelno | ``%(levelno)s`` | Numeric logging level for the message |
3646| | | (:const:`DEBUG`, :const:`INFO`, |
3647| | | :const:`WARNING`, :const:`ERROR`, |
3648| | | :const:`CRITICAL`). |
3649+----------------+-------------------------+-----------------------------------------------+
3650| lineno | ``%(lineno)d`` | Source line number where the logging call was |
3651| | | issued (if available). |
3652+----------------+-------------------------+-----------------------------------------------+
3653| module | ``%(module)s`` | Module (name portion of ``filename``). |
3654+----------------+-------------------------+-----------------------------------------------+
3655| msecs | ``%(msecs)d`` | Millisecond portion of the time when the |
3656| | | :class:`LogRecord` was created. |
3657+----------------+-------------------------+-----------------------------------------------+
3658| message | ``%(message)s`` | The logged message, computed as ``msg % |
3659| | | args``. This is set when |
3660| | | :meth:`Formatter.format` is invoked. |
3661+----------------+-------------------------+-----------------------------------------------+
3662| msg | You shouldn't need to | The format string passed in the original |
3663| | format this yourself. | logging call. Merged with ``args`` to |
3664| | | produce ``message``, or an arbitrary object |
3665| | | (see :ref:`arbitrary-object-messages`). |
3666+----------------+-------------------------+-----------------------------------------------+
3667| name | ``%(name)s`` | Name of the logger used to log the call. |
3668+----------------+-------------------------+-----------------------------------------------+
3669| pathname | ``%(pathname)s`` | Full pathname of the source file where the |
3670| | | logging call was issued (if available). |
3671+----------------+-------------------------+-----------------------------------------------+
3672| process | ``%(process)d`` | Process ID (if available). |
3673+----------------+-------------------------+-----------------------------------------------+
3674| processName | ``%(processName)s`` | Process name (if available). |
3675+----------------+-------------------------+-----------------------------------------------+
3676| relativeCreated| ``%(relativeCreated)d`` | Time in milliseconds when the LogRecord was |
3677| | | created, relative to the time the logging |
3678| | | module was loaded. |
3679+----------------+-------------------------+-----------------------------------------------+
3680| stack_info | You shouldn't need to | Stack frame information (where available) |
3681| | format this yourself. | from the bottom of the stack in the current |
3682| | | thread, up to and including the stack frame |
3683| | | of the logging call which resulted in the |
3684| | | creation of this record. |
3685+----------------+-------------------------+-----------------------------------------------+
3686| thread | ``%(thread)d`` | Thread ID (if available). |
3687+----------------+-------------------------+-----------------------------------------------+
3688| threadName | ``%(threadName)s`` | Thread name (if available). |
3689+----------------+-------------------------+-----------------------------------------------+
3690
3691
Vinay Sajipd31f3632010-06-29 15:31:15 +00003692.. _logger-adapter:
Georg Brandl116aa622007-08-15 14:28:22 +00003693
Christian Heimes04c420f2008-01-18 18:40:46 +00003694LoggerAdapter Objects
3695---------------------
3696
Christian Heimes04c420f2008-01-18 18:40:46 +00003697:class:`LoggerAdapter` instances are used to conveniently pass contextual
Georg Brandl86def6c2008-01-21 20:36:10 +00003698information into logging calls. For a usage example , see the section on
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003699:ref:`adding contextual information to your logging output <context-info>`.
Georg Brandl86def6c2008-01-21 20:36:10 +00003700
Christian Heimes04c420f2008-01-18 18:40:46 +00003701
3702.. class:: LoggerAdapter(logger, extra)
3703
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003704 Returns an instance of :class:`LoggerAdapter` initialized with an
3705 underlying :class:`Logger` instance and a dict-like object.
Christian Heimes04c420f2008-01-18 18:40:46 +00003706
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003707 .. method:: process(msg, kwargs)
Christian Heimes04c420f2008-01-18 18:40:46 +00003708
Georg Brandl1eb40bc2010-12-03 15:30:09 +00003709 Modifies the message and/or keyword arguments passed to a logging call in
3710 order to insert contextual information. This implementation takes the object
3711 passed as *extra* to the constructor and adds it to *kwargs* using key
3712 'extra'. The return value is a (*msg*, *kwargs*) tuple which has the
3713 (possibly modified) versions of the arguments passed in.
Christian Heimes04c420f2008-01-18 18:40:46 +00003714
Vinay Sajipc84f0162010-09-21 11:25:39 +00003715In addition to the above, :class:`LoggerAdapter` supports the following
Christian Heimes04c420f2008-01-18 18:40:46 +00003716methods of :class:`Logger`, i.e. :meth:`debug`, :meth:`info`, :meth:`warning`,
Vinay Sajipc84f0162010-09-21 11:25:39 +00003717:meth:`error`, :meth:`exception`, :meth:`critical`, :meth:`log`,
3718:meth:`isEnabledFor`, :meth:`getEffectiveLevel`, :meth:`setLevel`,
3719:meth:`hasHandlers`. These methods have the same signatures as their
3720counterparts in :class:`Logger`, so you can use the two types of instances
3721interchangeably.
Christian Heimes04c420f2008-01-18 18:40:46 +00003722
Ezio Melotti4d5195b2010-04-20 10:57:44 +00003723.. versionchanged:: 3.2
Vinay Sajipc84f0162010-09-21 11:25:39 +00003724 The :meth:`isEnabledFor`, :meth:`getEffectiveLevel`, :meth:`setLevel` and
3725 :meth:`hasHandlers` methods were added to :class:`LoggerAdapter`. These
3726 methods delegate to the underlying logger.
Benjamin Peterson22005fc2010-04-11 16:25:06 +00003727
Georg Brandl116aa622007-08-15 14:28:22 +00003728
3729Thread Safety
3730-------------
3731
3732The logging module is intended to be thread-safe without any special work
3733needing to be done by its clients. It achieves this though using threading
3734locks; there is one lock to serialize access to the module's shared data, and
3735each handler also creates a lock to serialize access to its underlying I/O.
3736
Benjamin Petersond23f8222009-04-05 19:13:16 +00003737If you are implementing asynchronous signal handlers using the :mod:`signal`
3738module, you may not be able to use logging from within such handlers. This is
3739because lock implementations in the :mod:`threading` module are not always
3740re-entrant, and so cannot be invoked from such signal handlers.
Georg Brandl116aa622007-08-15 14:28:22 +00003741
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00003742
3743Integration with the warnings module
3744------------------------------------
3745
3746The :func:`captureWarnings` function can be used to integrate :mod:`logging`
3747with the :mod:`warnings` module.
3748
3749.. function:: captureWarnings(capture)
3750
3751 This function is used to turn the capture of warnings by logging on and
3752 off.
3753
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003754 If *capture* is ``True``, warnings issued by the :mod:`warnings` module will
3755 be redirected to the logging system. Specifically, a warning will be
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00003756 formatted using :func:`warnings.formatwarning` and the resulting string
Vinay Sajip9a6b4002010-12-14 19:40:21 +00003757 logged to a logger named 'py.warnings' with a severity of `WARNING`.
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00003758
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003759 If *capture* is ``False``, the redirection of warnings to the logging system
Benjamin Peterson9451a1c2010-03-13 22:30:34 +00003760 will stop, and warnings will be redirected to their original destinations
3761 (i.e. those in effect before `captureWarnings(True)` was called).
3762
3763
Georg Brandl116aa622007-08-15 14:28:22 +00003764Configuration
3765-------------
3766
3767
3768.. _logging-config-api:
3769
3770Configuration functions
3771^^^^^^^^^^^^^^^^^^^^^^^
3772
Georg Brandl116aa622007-08-15 14:28:22 +00003773The following functions configure the logging module. They are located in the
3774:mod:`logging.config` module. Their use is optional --- you can configure the
3775logging module using these functions or by making calls to the main API (defined
3776in :mod:`logging` itself) and defining handlers which are declared either in
3777:mod:`logging` or :mod:`logging.handlers`.
3778
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003779.. function:: dictConfig(config)
Georg Brandl116aa622007-08-15 14:28:22 +00003780
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003781 Takes the logging configuration from a dictionary. The contents of
3782 this dictionary are described in :ref:`logging-config-dictschema`
3783 below.
3784
3785 If an error is encountered during configuration, this function will
3786 raise a :exc:`ValueError`, :exc:`TypeError`, :exc:`AttributeError`
3787 or :exc:`ImportError` with a suitably descriptive message. The
3788 following is a (possibly incomplete) list of conditions which will
3789 raise an error:
3790
3791 * A ``level`` which is not a string or which is a string not
3792 corresponding to an actual logging level.
3793 * A ``propagate`` value which is not a boolean.
3794 * An id which does not have a corresponding destination.
3795 * A non-existent handler id found during an incremental call.
3796 * An invalid logger name.
3797 * Inability to resolve to an internal or external object.
3798
3799 Parsing is performed by the :class:`DictConfigurator` class, whose
3800 constructor is passed the dictionary used for configuration, and
3801 has a :meth:`configure` method. The :mod:`logging.config` module
3802 has a callable attribute :attr:`dictConfigClass`
3803 which is initially set to :class:`DictConfigurator`.
3804 You can replace the value of :attr:`dictConfigClass` with a
3805 suitable implementation of your own.
3806
3807 :func:`dictConfig` calls :attr:`dictConfigClass` passing
3808 the specified dictionary, and then calls the :meth:`configure` method on
3809 the returned object to put the configuration into effect::
3810
3811 def dictConfig(config):
3812 dictConfigClass(config).configure()
3813
3814 For example, a subclass of :class:`DictConfigurator` could call
3815 ``DictConfigurator.__init__()`` in its own :meth:`__init__()`, then
3816 set up custom prefixes which would be usable in the subsequent
3817 :meth:`configure` call. :attr:`dictConfigClass` would be bound to
3818 this new subclass, and then :func:`dictConfig` could be called exactly as
3819 in the default, uncustomized state.
3820
3821.. function:: fileConfig(fname[, defaults])
Georg Brandl116aa622007-08-15 14:28:22 +00003822
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00003823 Reads the logging configuration from a :mod:`configparser`\-format file named
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00003824 *fname*. This function can be called several times from an application,
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003825 allowing an end user to select from various pre-canned
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00003826 configurations (if the developer provides a mechanism to present the choices
3827 and load the chosen configuration). Defaults to be passed to the ConfigParser
3828 can be specified in the *defaults* argument.
Georg Brandl116aa622007-08-15 14:28:22 +00003829
Georg Brandlcd7f32b2009-06-08 09:13:45 +00003830
3831.. function:: listen(port=DEFAULT_LOGGING_CONFIG_PORT)
Georg Brandl116aa622007-08-15 14:28:22 +00003832
3833 Starts up a socket server on the specified port, and listens for new
3834 configurations. If no port is specified, the module's default
3835 :const:`DEFAULT_LOGGING_CONFIG_PORT` is used. Logging configurations will be
3836 sent as a file suitable for processing by :func:`fileConfig`. Returns a
3837 :class:`Thread` instance on which you can call :meth:`start` to start the
3838 server, and which you can :meth:`join` when appropriate. To stop the server,
Christian Heimes8b0facf2007-12-04 19:30:01 +00003839 call :func:`stopListening`.
3840
3841 To send a configuration to the socket, read in the configuration file and
3842 send it to the socket as a string of bytes preceded by a four-byte length
3843 string packed in binary using ``struct.pack('>L', n)``.
Georg Brandl116aa622007-08-15 14:28:22 +00003844
3845
3846.. function:: stopListening()
3847
Christian Heimes8b0facf2007-12-04 19:30:01 +00003848 Stops the listening server which was created with a call to :func:`listen`.
3849 This is typically called before calling :meth:`join` on the return value from
Georg Brandl116aa622007-08-15 14:28:22 +00003850 :func:`listen`.
3851
3852
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003853.. _logging-config-dictschema:
3854
3855Configuration dictionary schema
3856^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3857
3858Describing a logging configuration requires listing the various
3859objects to create and the connections between them; for example, you
Vinay Sajip9a6b4002010-12-14 19:40:21 +00003860may create a handler named 'console' and then say that the logger
3861named 'startup' will send its messages to the 'console' handler.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003862These objects aren't limited to those provided by the :mod:`logging`
3863module because you might write your own formatter or handler class.
3864The parameters to these classes may also need to include external
3865objects such as ``sys.stderr``. The syntax for describing these
3866objects and connections is defined in :ref:`logging-config-dict-connections`
3867below.
3868
3869Dictionary Schema Details
3870"""""""""""""""""""""""""
3871
3872The dictionary passed to :func:`dictConfig` must contain the following
3873keys:
3874
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003875* *version* - to be set to an integer value representing the schema
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003876 version. The only valid value at present is 1, but having this key
3877 allows the schema to evolve while still preserving backwards
3878 compatibility.
3879
3880All other keys are optional, but if present they will be interpreted
3881as described below. In all cases below where a 'configuring dict' is
3882mentioned, it will be checked for the special ``'()'`` key to see if a
3883custom instantiation is required. If so, the mechanism described in
3884:ref:`logging-config-dict-userdef` below is used to create an instance;
3885otherwise, the context is used to determine what to instantiate.
3886
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003887* *formatters* - the corresponding value will be a dict in which each
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003888 key is a formatter id and each value is a dict describing how to
3889 configure the corresponding Formatter instance.
3890
3891 The configuring dict is searched for keys ``format`` and ``datefmt``
3892 (with defaults of ``None``) and these are used to construct a
3893 :class:`logging.Formatter` instance.
3894
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003895* *filters* - the corresponding value will be a dict in which each key
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003896 is a filter id and each value is a dict describing how to configure
3897 the corresponding Filter instance.
3898
3899 The configuring dict is searched for the key ``name`` (defaulting to the
3900 empty string) and this is used to construct a :class:`logging.Filter`
3901 instance.
3902
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003903* *handlers* - the corresponding value will be a dict in which each
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003904 key is a handler id and each value is a dict describing how to
3905 configure the corresponding Handler instance.
3906
3907 The configuring dict is searched for the following keys:
3908
3909 * ``class`` (mandatory). This is the fully qualified name of the
3910 handler class.
3911
3912 * ``level`` (optional). The level of the handler.
3913
3914 * ``formatter`` (optional). The id of the formatter for this
3915 handler.
3916
3917 * ``filters`` (optional). A list of ids of the filters for this
3918 handler.
3919
3920 All *other* keys are passed through as keyword arguments to the
3921 handler's constructor. For example, given the snippet::
3922
3923 handlers:
3924 console:
3925 class : logging.StreamHandler
3926 formatter: brief
3927 level : INFO
3928 filters: [allow_foo]
3929 stream : ext://sys.stdout
3930 file:
3931 class : logging.handlers.RotatingFileHandler
3932 formatter: precise
3933 filename: logconfig.log
3934 maxBytes: 1024
3935 backupCount: 3
3936
3937 the handler with id ``console`` is instantiated as a
3938 :class:`logging.StreamHandler`, using ``sys.stdout`` as the underlying
3939 stream. The handler with id ``file`` is instantiated as a
3940 :class:`logging.handlers.RotatingFileHandler` with the keyword arguments
3941 ``filename='logconfig.log', maxBytes=1024, backupCount=3``.
3942
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003943* *loggers* - the corresponding value will be a dict in which each key
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003944 is a logger name and each value is a dict describing how to
3945 configure the corresponding Logger instance.
3946
3947 The configuring dict is searched for the following keys:
3948
3949 * ``level`` (optional). The level of the logger.
3950
3951 * ``propagate`` (optional). The propagation setting of the logger.
3952
3953 * ``filters`` (optional). A list of ids of the filters for this
3954 logger.
3955
3956 * ``handlers`` (optional). A list of ids of the handlers for this
3957 logger.
3958
3959 The specified loggers will be configured according to the level,
3960 propagation, filters and handlers specified.
3961
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003962* *root* - this will be the configuration for the root logger.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003963 Processing of the configuration will be as for any logger, except
3964 that the ``propagate`` setting will not be applicable.
3965
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003966* *incremental* - whether the configuration is to be interpreted as
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003967 incremental to the existing configuration. This value defaults to
3968 ``False``, which means that the specified configuration replaces the
3969 existing configuration with the same semantics as used by the
3970 existing :func:`fileConfig` API.
3971
3972 If the specified value is ``True``, the configuration is processed
3973 as described in the section on :ref:`logging-config-dict-incremental`.
3974
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003975* *disable_existing_loggers* - whether any existing loggers are to be
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003976 disabled. This setting mirrors the parameter of the same name in
3977 :func:`fileConfig`. If absent, this parameter defaults to ``True``.
Senthil Kumaran46a48be2010-10-15 13:10:10 +00003978 This value is ignored if *incremental* is ``True``.
Benjamin Petersond7c3ed52010-06-27 22:32:30 +00003979
3980.. _logging-config-dict-incremental:
3981
3982Incremental Configuration
3983"""""""""""""""""""""""""
3984
3985It is difficult to provide complete flexibility for incremental
3986configuration. For example, because objects such as filters
3987and formatters are anonymous, once a configuration is set up, it is
3988not possible to refer to such anonymous objects when augmenting a
3989configuration.
3990
3991Furthermore, there is not a compelling case for arbitrarily altering
3992the object graph of loggers, handlers, filters, formatters at
3993run-time, once a configuration is set up; the verbosity of loggers and
3994handlers can be controlled just by setting levels (and, in the case of
3995loggers, propagation flags). Changing the object graph arbitrarily in
3996a safe way is problematic in a multi-threaded environment; while not
3997impossible, the benefits are not worth the complexity it adds to the
3998implementation.
3999
4000Thus, when the ``incremental`` key of a configuration dict is present
4001and is ``True``, the system will completely ignore any ``formatters`` and
4002``filters`` entries, and process only the ``level``
4003settings in the ``handlers`` entries, and the ``level`` and
4004``propagate`` settings in the ``loggers`` and ``root`` entries.
4005
4006Using a value in the configuration dict lets configurations to be sent
4007over the wire as pickled dicts to a socket listener. Thus, the logging
4008verbosity of a long-running application can be altered over time with
4009no need to stop and restart the application.
4010
4011.. _logging-config-dict-connections:
4012
4013Object connections
4014""""""""""""""""""
4015
4016The schema describes a set of logging objects - loggers,
4017handlers, formatters, filters - which are connected to each other in
4018an object graph. Thus, the schema needs to represent connections
4019between the objects. For example, say that, once configured, a
4020particular logger has attached to it a particular handler. For the
4021purposes of this discussion, we can say that the logger represents the
4022source, and the handler the destination, of a connection between the
4023two. Of course in the configured objects this is represented by the
4024logger holding a reference to the handler. In the configuration dict,
4025this is done by giving each destination object an id which identifies
4026it unambiguously, and then using the id in the source object's
4027configuration to indicate that a connection exists between the source
4028and the destination object with that id.
4029
4030So, for example, consider the following YAML snippet::
4031
4032 formatters:
4033 brief:
4034 # configuration for formatter with id 'brief' goes here
4035 precise:
4036 # configuration for formatter with id 'precise' goes here
4037 handlers:
4038 h1: #This is an id
4039 # configuration of handler with id 'h1' goes here
4040 formatter: brief
4041 h2: #This is another id
4042 # configuration of handler with id 'h2' goes here
4043 formatter: precise
4044 loggers:
4045 foo.bar.baz:
4046 # other configuration for logger 'foo.bar.baz'
4047 handlers: [h1, h2]
4048
4049(Note: YAML used here because it's a little more readable than the
4050equivalent Python source form for the dictionary.)
4051
4052The ids for loggers are the logger names which would be used
4053programmatically to obtain a reference to those loggers, e.g.
4054``foo.bar.baz``. The ids for Formatters and Filters can be any string
4055value (such as ``brief``, ``precise`` above) and they are transient,
4056in that they are only meaningful for processing the configuration
4057dictionary and used to determine connections between objects, and are
4058not persisted anywhere when the configuration call is complete.
4059
4060The above snippet indicates that logger named ``foo.bar.baz`` should
4061have two handlers attached to it, which are described by the handler
4062ids ``h1`` and ``h2``. The formatter for ``h1`` is that described by id
4063``brief``, and the formatter for ``h2`` is that described by id
4064``precise``.
4065
4066
4067.. _logging-config-dict-userdef:
4068
4069User-defined objects
4070""""""""""""""""""""
4071
4072The schema supports user-defined objects for handlers, filters and
4073formatters. (Loggers do not need to have different types for
4074different instances, so there is no support in this configuration
4075schema for user-defined logger classes.)
4076
4077Objects to be configured are described by dictionaries
4078which detail their configuration. In some places, the logging system
4079will be able to infer from the context how an object is to be
4080instantiated, but when a user-defined object is to be instantiated,
4081the system will not know how to do this. In order to provide complete
4082flexibility for user-defined object instantiation, the user needs
4083to provide a 'factory' - a callable which is called with a
4084configuration dictionary and which returns the instantiated object.
4085This is signalled by an absolute import path to the factory being
4086made available under the special key ``'()'``. Here's a concrete
4087example::
4088
4089 formatters:
4090 brief:
4091 format: '%(message)s'
4092 default:
4093 format: '%(asctime)s %(levelname)-8s %(name)-15s %(message)s'
4094 datefmt: '%Y-%m-%d %H:%M:%S'
4095 custom:
4096 (): my.package.customFormatterFactory
4097 bar: baz
4098 spam: 99.9
4099 answer: 42
4100
4101The above YAML snippet defines three formatters. The first, with id
4102``brief``, is a standard :class:`logging.Formatter` instance with the
4103specified format string. The second, with id ``default``, has a
4104longer format and also defines the time format explicitly, and will
4105result in a :class:`logging.Formatter` initialized with those two format
4106strings. Shown in Python source form, the ``brief`` and ``default``
4107formatters have configuration sub-dictionaries::
4108
4109 {
4110 'format' : '%(message)s'
4111 }
4112
4113and::
4114
4115 {
4116 'format' : '%(asctime)s %(levelname)-8s %(name)-15s %(message)s',
4117 'datefmt' : '%Y-%m-%d %H:%M:%S'
4118 }
4119
4120respectively, and as these dictionaries do not contain the special key
4121``'()'``, the instantiation is inferred from the context: as a result,
4122standard :class:`logging.Formatter` instances are created. The
4123configuration sub-dictionary for the third formatter, with id
4124``custom``, is::
4125
4126 {
4127 '()' : 'my.package.customFormatterFactory',
4128 'bar' : 'baz',
4129 'spam' : 99.9,
4130 'answer' : 42
4131 }
4132
4133and this contains the special key ``'()'``, which means that
4134user-defined instantiation is wanted. In this case, the specified
4135factory callable will be used. If it is an actual callable it will be
4136used directly - otherwise, if you specify a string (as in the example)
4137the actual callable will be located using normal import mechanisms.
4138The callable will be called with the **remaining** items in the
4139configuration sub-dictionary as keyword arguments. In the above
4140example, the formatter with id ``custom`` will be assumed to be
4141returned by the call::
4142
4143 my.package.customFormatterFactory(bar='baz', spam=99.9, answer=42)
4144
4145The key ``'()'`` has been used as the special key because it is not a
4146valid keyword parameter name, and so will not clash with the names of
4147the keyword arguments used in the call. The ``'()'`` also serves as a
4148mnemonic that the corresponding value is a callable.
4149
4150
4151.. _logging-config-dict-externalobj:
4152
4153Access to external objects
4154""""""""""""""""""""""""""
4155
4156There are times where a configuration needs to refer to objects
4157external to the configuration, for example ``sys.stderr``. If the
4158configuration dict is constructed using Python code, this is
4159straightforward, but a problem arises when the configuration is
4160provided via a text file (e.g. JSON, YAML). In a text file, there is
4161no standard way to distinguish ``sys.stderr`` from the literal string
4162``'sys.stderr'``. To facilitate this distinction, the configuration
4163system looks for certain special prefixes in string values and
4164treat them specially. For example, if the literal string
4165``'ext://sys.stderr'`` is provided as a value in the configuration,
4166then the ``ext://`` will be stripped off and the remainder of the
4167value processed using normal import mechanisms.
4168
4169The handling of such prefixes is done in a way analogous to protocol
4170handling: there is a generic mechanism to look for prefixes which
4171match the regular expression ``^(?P<prefix>[a-z]+)://(?P<suffix>.*)$``
4172whereby, if the ``prefix`` is recognised, the ``suffix`` is processed
4173in a prefix-dependent manner and the result of the processing replaces
4174the string value. If the prefix is not recognised, then the string
4175value will be left as-is.
4176
4177
4178.. _logging-config-dict-internalobj:
4179
4180Access to internal objects
4181""""""""""""""""""""""""""
4182
4183As well as external objects, there is sometimes also a need to refer
4184to objects in the configuration. This will be done implicitly by the
4185configuration system for things that it knows about. For example, the
4186string value ``'DEBUG'`` for a ``level`` in a logger or handler will
4187automatically be converted to the value ``logging.DEBUG``, and the
4188``handlers``, ``filters`` and ``formatter`` entries will take an
4189object id and resolve to the appropriate destination object.
4190
4191However, a more generic mechanism is needed for user-defined
4192objects which are not known to the :mod:`logging` module. For
4193example, consider :class:`logging.handlers.MemoryHandler`, which takes
4194a ``target`` argument which is another handler to delegate to. Since
4195the system already knows about this class, then in the configuration,
4196the given ``target`` just needs to be the object id of the relevant
4197target handler, and the system will resolve to the handler from the
4198id. If, however, a user defines a ``my.package.MyHandler`` which has
4199an ``alternate`` handler, the configuration system would not know that
4200the ``alternate`` referred to a handler. To cater for this, a generic
4201resolution system allows the user to specify::
4202
4203 handlers:
4204 file:
4205 # configuration of file handler goes here
4206
4207 custom:
4208 (): my.package.MyHandler
4209 alternate: cfg://handlers.file
4210
4211The literal string ``'cfg://handlers.file'`` will be resolved in an
4212analogous way to strings with the ``ext://`` prefix, but looking
4213in the configuration itself rather than the import namespace. The
4214mechanism allows access by dot or by index, in a similar way to
4215that provided by ``str.format``. Thus, given the following snippet::
4216
4217 handlers:
4218 email:
4219 class: logging.handlers.SMTPHandler
4220 mailhost: localhost
4221 fromaddr: my_app@domain.tld
4222 toaddrs:
4223 - support_team@domain.tld
4224 - dev_team@domain.tld
4225 subject: Houston, we have a problem.
4226
4227in the configuration, the string ``'cfg://handlers'`` would resolve to
4228the dict with key ``handlers``, the string ``'cfg://handlers.email``
4229would resolve to the dict with key ``email`` in the ``handlers`` dict,
4230and so on. The string ``'cfg://handlers.email.toaddrs[1]`` would
4231resolve to ``'dev_team.domain.tld'`` and the string
4232``'cfg://handlers.email.toaddrs[0]'`` would resolve to the value
4233``'support_team@domain.tld'``. The ``subject`` value could be accessed
4234using either ``'cfg://handlers.email.subject'`` or, equivalently,
4235``'cfg://handlers.email[subject]'``. The latter form only needs to be
4236used if the key contains spaces or non-alphanumeric characters. If an
4237index value consists only of decimal digits, access will be attempted
4238using the corresponding integer value, falling back to the string
4239value if needed.
4240
4241Given a string ``cfg://handlers.myhandler.mykey.123``, this will
4242resolve to ``config_dict['handlers']['myhandler']['mykey']['123']``.
4243If the string is specified as ``cfg://handlers.myhandler.mykey[123]``,
4244the system will attempt to retrieve the value from
4245``config_dict['handlers']['myhandler']['mykey'][123]``, and fall back
4246to ``config_dict['handlers']['myhandler']['mykey']['123']`` if that
4247fails.
4248
Georg Brandl116aa622007-08-15 14:28:22 +00004249.. _logging-config-fileformat:
4250
4251Configuration file format
4252^^^^^^^^^^^^^^^^^^^^^^^^^
4253
Benjamin Peterson960cf0f2009-01-09 04:11:44 +00004254The configuration file format understood by :func:`fileConfig` is based on
4255:mod:`configparser` functionality. The file must contain sections called
4256``[loggers]``, ``[handlers]`` and ``[formatters]`` which identify by name the
4257entities of each type which are defined in the file. For each such entity, there
4258is a separate section which identifies how that entity is configured. Thus, for
4259a logger named ``log01`` in the ``[loggers]`` section, the relevant
4260configuration details are held in a section ``[logger_log01]``. Similarly, a
4261handler called ``hand01`` in the ``[handlers]`` section will have its
4262configuration held in a section called ``[handler_hand01]``, while a formatter
4263called ``form01`` in the ``[formatters]`` section will have its configuration
4264specified in a section called ``[formatter_form01]``. The root logger
4265configuration must be specified in a section called ``[logger_root]``.
Georg Brandl116aa622007-08-15 14:28:22 +00004266
4267Examples of these sections in the file are given below. ::
4268
4269 [loggers]
4270 keys=root,log02,log03,log04,log05,log06,log07
4271
4272 [handlers]
4273 keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
4274
4275 [formatters]
4276 keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
4277
4278The root logger must specify a level and a list of handlers. An example of a
4279root logger section is given below. ::
4280
4281 [logger_root]
4282 level=NOTSET
4283 handlers=hand01
4284
4285The ``level`` entry can be one of ``DEBUG, INFO, WARNING, ERROR, CRITICAL`` or
4286``NOTSET``. For the root logger only, ``NOTSET`` means that all messages will be
4287logged. Level values are :func:`eval`\ uated in the context of the ``logging``
4288package's namespace.
4289
4290The ``handlers`` entry is a comma-separated list of handler names, which must
4291appear in the ``[handlers]`` section. These names must appear in the
4292``[handlers]`` section and have corresponding sections in the configuration
4293file.
4294
4295For loggers other than the root logger, some additional information is required.
4296This is illustrated by the following example. ::
4297
4298 [logger_parser]
4299 level=DEBUG
4300 handlers=hand01
4301 propagate=1
4302 qualname=compiler.parser
4303
4304The ``level`` and ``handlers`` entries are interpreted as for the root logger,
4305except that if a non-root logger's level is specified as ``NOTSET``, the system
4306consults loggers higher up the hierarchy to determine the effective level of the
4307logger. The ``propagate`` entry is set to 1 to indicate that messages must
4308propagate to handlers higher up the logger hierarchy from this logger, or 0 to
4309indicate that messages are **not** propagated to handlers up the hierarchy. The
4310``qualname`` entry is the hierarchical channel name of the logger, that is to
4311say the name used by the application to get the logger.
4312
4313Sections which specify handler configuration are exemplified by the following.
4314::
4315
4316 [handler_hand01]
4317 class=StreamHandler
4318 level=NOTSET
4319 formatter=form01
4320 args=(sys.stdout,)
4321
4322The ``class`` entry indicates the handler's class (as determined by :func:`eval`
4323in the ``logging`` package's namespace). The ``level`` is interpreted as for
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004324loggers, and ``NOTSET`` is taken to mean 'log everything'.
Georg Brandl116aa622007-08-15 14:28:22 +00004325
4326The ``formatter`` entry indicates the key name of the formatter for this
4327handler. If blank, a default formatter (``logging._defaultFormatter``) is used.
4328If a name is specified, it must appear in the ``[formatters]`` section and have
4329a corresponding section in the configuration file.
4330
4331The ``args`` entry, when :func:`eval`\ uated in the context of the ``logging``
4332package's namespace, is the list of arguments to the constructor for the handler
4333class. Refer to the constructors for the relevant handlers, or to the examples
4334below, to see how typical entries are constructed. ::
4335
4336 [handler_hand02]
4337 class=FileHandler
4338 level=DEBUG
4339 formatter=form02
4340 args=('python.log', 'w')
4341
4342 [handler_hand03]
4343 class=handlers.SocketHandler
4344 level=INFO
4345 formatter=form03
4346 args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
4347
4348 [handler_hand04]
4349 class=handlers.DatagramHandler
4350 level=WARN
4351 formatter=form04
4352 args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
4353
4354 [handler_hand05]
4355 class=handlers.SysLogHandler
4356 level=ERROR
4357 formatter=form05
4358 args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
4359
4360 [handler_hand06]
4361 class=handlers.NTEventLogHandler
4362 level=CRITICAL
4363 formatter=form06
4364 args=('Python Application', '', 'Application')
4365
4366 [handler_hand07]
4367 class=handlers.SMTPHandler
4368 level=WARN
4369 formatter=form07
4370 args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
4371
4372 [handler_hand08]
4373 class=handlers.MemoryHandler
4374 level=NOTSET
4375 formatter=form08
4376 target=
4377 args=(10, ERROR)
4378
4379 [handler_hand09]
4380 class=handlers.HTTPHandler
4381 level=NOTSET
4382 formatter=form09
4383 args=('localhost:9022', '/log', 'GET')
4384
4385Sections which specify formatter configuration are typified by the following. ::
4386
4387 [formatter_form01]
4388 format=F1 %(asctime)s %(levelname)s %(message)s
4389 datefmt=
4390 class=logging.Formatter
4391
4392The ``format`` entry is the overall format string, and the ``datefmt`` entry is
Christian Heimes5b5e81c2007-12-31 16:14:33 +00004393the :func:`strftime`\ -compatible date/time format string. If empty, the
4394package substitutes ISO8601 format date/times, which is almost equivalent to
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004395specifying the date format string ``'%Y-%m-%d %H:%M:%S'``. The ISO8601 format
Christian Heimes5b5e81c2007-12-31 16:14:33 +00004396also specifies milliseconds, which are appended to the result of using the above
4397format string, with a comma separator. An example time in ISO8601 format is
4398``2003-01-23 00:29:50,411``.
Georg Brandl116aa622007-08-15 14:28:22 +00004399
4400The ``class`` entry is optional. It indicates the name of the formatter's class
4401(as a dotted module and class name.) This option is useful for instantiating a
4402:class:`Formatter` subclass. Subclasses of :class:`Formatter` can present
4403exception tracebacks in an expanded or condensed format.
4404
Christian Heimes8b0facf2007-12-04 19:30:01 +00004405
4406Configuration server example
4407^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4408
4409Here is an example of a module using the logging configuration server::
4410
4411 import logging
4412 import logging.config
4413 import time
4414 import os
4415
4416 # read initial config file
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004417 logging.config.fileConfig('logging.conf')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004418
4419 # create and start listener on port 9999
4420 t = logging.config.listen(9999)
4421 t.start()
4422
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004423 logger = logging.getLogger('simpleExample')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004424
4425 try:
4426 # loop through logging calls to see the difference
4427 # new configurations make, until Ctrl+C is pressed
4428 while True:
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004429 logger.debug('debug message')
4430 logger.info('info message')
4431 logger.warn('warn message')
4432 logger.error('error message')
4433 logger.critical('critical message')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004434 time.sleep(5)
4435 except KeyboardInterrupt:
4436 # cleanup
4437 logging.config.stopListening()
4438 t.join()
4439
4440And here is a script that takes a filename and sends that file to the server,
4441properly preceded with the binary-encoded length, as the new logging
4442configuration::
4443
4444 #!/usr/bin/env python
4445 import socket, sys, struct
4446
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004447 data_to_send = open(sys.argv[1], 'r').read()
Christian Heimes8b0facf2007-12-04 19:30:01 +00004448
4449 HOST = 'localhost'
4450 PORT = 9999
4451 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004452 print('connecting...')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004453 s.connect((HOST, PORT))
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004454 print('sending config...')
4455 s.send(struct.pack('>L', len(data_to_send)))
Christian Heimes8b0facf2007-12-04 19:30:01 +00004456 s.send(data_to_send)
4457 s.close()
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004458 print('complete')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004459
4460
4461More examples
4462-------------
4463
4464Multiple handlers and formatters
4465^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4466
4467Loggers are plain Python objects. The :func:`addHandler` method has no minimum
4468or maximum quota for the number of handlers you may add. Sometimes it will be
4469beneficial for an application to log all messages of all severities to a text
4470file while simultaneously logging errors or above to the console. To set this
4471up, simply configure the appropriate handlers. The logging calls in the
4472application code will remain unchanged. Here is a slight modification to the
4473previous simple module-based configuration example::
4474
4475 import logging
4476
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004477 logger = logging.getLogger('simple_example')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004478 logger.setLevel(logging.DEBUG)
4479 # create file handler which logs even debug messages
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004480 fh = logging.FileHandler('spam.log')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004481 fh.setLevel(logging.DEBUG)
4482 # create console handler with a higher log level
4483 ch = logging.StreamHandler()
4484 ch.setLevel(logging.ERROR)
4485 # create formatter and add it to the handlers
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004486 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004487 ch.setFormatter(formatter)
4488 fh.setFormatter(formatter)
4489 # add the handlers to logger
4490 logger.addHandler(ch)
4491 logger.addHandler(fh)
4492
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004493 # 'application' code
4494 logger.debug('debug message')
4495 logger.info('info message')
4496 logger.warn('warn message')
4497 logger.error('error message')
4498 logger.critical('critical message')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004499
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004500Notice that the 'application' code does not care about multiple handlers. All
Christian Heimes8b0facf2007-12-04 19:30:01 +00004501that changed was the addition and configuration of a new handler named *fh*.
4502
4503The ability to create new handlers with higher- or lower-severity filters can be
4504very helpful when writing and testing an application. Instead of using many
4505``print`` statements for debugging, use ``logger.debug``: Unlike the print
4506statements, which you will have to delete or comment out later, the logger.debug
4507statements can remain intact in the source code and remain dormant until you
4508need them again. At that time, the only change that needs to happen is to
4509modify the severity level of the logger and/or handler to debug.
4510
4511
4512Using logging in multiple modules
4513^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4514
4515It was mentioned above that multiple calls to
4516``logging.getLogger('someLogger')`` return a reference to the same logger
4517object. This is true not only within the same module, but also across modules
4518as long as it is in the same Python interpreter process. It is true for
4519references to the same object; additionally, application code can define and
4520configure a parent logger in one module and create (but not configure) a child
4521logger in a separate module, and all logger calls to the child will pass up to
4522the parent. Here is a main module::
4523
4524 import logging
4525 import auxiliary_module
4526
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004527 # create logger with 'spam_application'
4528 logger = logging.getLogger('spam_application')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004529 logger.setLevel(logging.DEBUG)
4530 # create file handler which logs even debug messages
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004531 fh = logging.FileHandler('spam.log')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004532 fh.setLevel(logging.DEBUG)
4533 # create console handler with a higher log level
4534 ch = logging.StreamHandler()
4535 ch.setLevel(logging.ERROR)
4536 # create formatter and add it to the handlers
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004537 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004538 fh.setFormatter(formatter)
4539 ch.setFormatter(formatter)
4540 # add the handlers to the logger
4541 logger.addHandler(fh)
4542 logger.addHandler(ch)
4543
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004544 logger.info('creating an instance of auxiliary_module.Auxiliary')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004545 a = auxiliary_module.Auxiliary()
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004546 logger.info('created an instance of auxiliary_module.Auxiliary')
4547 logger.info('calling auxiliary_module.Auxiliary.do_something')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004548 a.do_something()
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004549 logger.info('finished auxiliary_module.Auxiliary.do_something')
4550 logger.info('calling auxiliary_module.some_function()')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004551 auxiliary_module.some_function()
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004552 logger.info('done with auxiliary_module.some_function()')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004553
4554Here is the auxiliary module::
4555
4556 import logging
4557
4558 # create logger
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004559 module_logger = logging.getLogger('spam_application.auxiliary')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004560
4561 class Auxiliary:
4562 def __init__(self):
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004563 self.logger = logging.getLogger('spam_application.auxiliary.Auxiliary')
4564 self.logger.info('creating an instance of Auxiliary')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004565 def do_something(self):
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004566 self.logger.info('doing something')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004567 a = 1 + 1
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004568 self.logger.info('done doing something')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004569
4570 def some_function():
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004571 module_logger.info('received a call to "some_function"')
Christian Heimes8b0facf2007-12-04 19:30:01 +00004572
4573The output looks like this::
4574
Christian Heimes043d6f62008-01-07 17:19:16 +00004575 2005-03-23 23:47:11,663 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004576 creating an instance of auxiliary_module.Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00004577 2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004578 creating an instance of Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00004579 2005-03-23 23:47:11,665 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004580 created an instance of auxiliary_module.Auxiliary
Christian Heimes043d6f62008-01-07 17:19:16 +00004581 2005-03-23 23:47:11,668 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004582 calling auxiliary_module.Auxiliary.do_something
Christian Heimes043d6f62008-01-07 17:19:16 +00004583 2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004584 doing something
Christian Heimes043d6f62008-01-07 17:19:16 +00004585 2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004586 done doing something
Christian Heimes043d6f62008-01-07 17:19:16 +00004587 2005-03-23 23:47:11,670 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004588 finished auxiliary_module.Auxiliary.do_something
Christian Heimes043d6f62008-01-07 17:19:16 +00004589 2005-03-23 23:47:11,671 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004590 calling auxiliary_module.some_function()
Christian Heimes043d6f62008-01-07 17:19:16 +00004591 2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
Vinay Sajip9a6b4002010-12-14 19:40:21 +00004592 received a call to 'some_function'
Christian Heimes043d6f62008-01-07 17:19:16 +00004593 2005-03-23 23:47:11,673 - spam_application - INFO -
Christian Heimes8b0facf2007-12-04 19:30:01 +00004594 done with auxiliary_module.some_function()
4595