rest25/library/logging.rst => rest262/library/logging.rst
n1- 
2:mod:`logging` --- Logging facility for Python
3==============================================
4
5.. module:: logging
n5+   :synopsis: Flexible error logging system for applications.
6
7
8.. moduleauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
9.. sectionauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
10
11
n12-.. % These apply to all modules, and may be given more than once:
13- 
14- 
15- 
16.. index:: pair: Errors; logging
17
18.. versionadded:: 2.3
19
20This module defines functions and classes which implement a flexible error
21logging system for applications.
22
23Logging is performed by calling methods on instances of the :class:`Logger`
24class (hereafter called :dfn:`loggers`). Each instance has a name, and they are
n25-conceptually arranged in a name space hierarchy using dots (periods) as
n21+conceptually arranged in a namespace hierarchy using dots (periods) as
26separators. For example, a logger named "scan" is the parent of loggers
27"scan.text", "scan.html" and "scan.pdf". Logger names can be anything you want,
28and indicate the area of an application in which a logged message originates.
29
30Logged messages also have levels of importance associated with them. The default
31levels provided are :const:`DEBUG`, :const:`INFO`, :const:`WARNING`,
32:const:`ERROR` and :const:`CRITICAL`. As a convenience, you indicate the
33importance of a logged message by calling an appropriate method of
34:class:`Logger`. The methods are :meth:`debug`, :meth:`info`, :meth:`warning`,
35:meth:`error` and :meth:`critical`, which mirror the default levels. You are not
36constrained to use these levels: you can specify your own and use a more general
37:class:`Logger` method, :meth:`log`, which takes an explicit level argument.
n34+ 
35+ 
36+Logging tutorial
37+----------------
38+ 
39+The key benefit of having the logging API provided by a standard library module
40+is that all Python modules can participate in logging, so your application log
41+can include messages from third-party modules.
42+ 
43+It is, of course, possible to log messages with different verbosity levels or to
44+different destinations.  Support for writing log messages to files, HTTP
45+GET/POST locations, email via SMTP, generic sockets, or OS-specific logging
46+mechanisms are all supported by the standard module.  You can also create your
47+own log destination class if you have special requirements not met by any of the
48+built-in classes.
49+ 
50+Simple examples
51+^^^^^^^^^^^^^^^
52+ 
53+.. sectionauthor:: Doug Hellmann
54+.. (see <http://blog.doughellmann.com/2007/05/pymotw-logging.html>)
55+ 
56+Most applications are probably going to want to log to a file, so let's start
57+with that case. Using the :func:`basicConfig` function, we can set up the
58+default handler so that debug messages are written to a file::
59+ 
60+   import logging
61+   LOG_FILENAME = '/tmp/logging_example.out'
62+   logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG,)
63+ 
64+   logging.debug('This message should go to the log file')
65+ 
66+And now if we open the file and look at what we have, we should find the log
67+message::
68+ 
69+   DEBUG:root:This message should go to the log file
70+ 
71+If you run the script repeatedly, the additional log messages are appended to
72+the file.  To create a new file each time, you can pass a filemode argument to
73+:func:`basicConfig` with a value of ``'w'``.  Rather than managing the file size
74+yourself, though, it is simpler to use a :class:`RotatingFileHandler`::
75+ 
76+   import glob
77+   import logging
78+   import logging.handlers
79+ 
80+   LOG_FILENAME = '/tmp/logging_rotatingfile_example.out'
81+ 
82+   # Set up a specific logger with our desired output level
83+   my_logger = logging.getLogger('MyLogger')
84+   my_logger.setLevel(logging.DEBUG)
85+ 
86+   # Add the log message handler to the logger
87+   handler = logging.handlers.RotatingFileHandler(
88+                 LOG_FILENAME, maxBytes=20, backupCount=5)
89+ 
90+   my_logger.addHandler(handler)
91+ 
92+   # Log some messages
93+   for i in range(20):
94+       my_logger.debug('i = %d' % i)
95+ 
96+   # See what files are created
97+   logfiles = glob.glob('%s*' % LOG_FILENAME)
98+ 
99+   for filename in logfiles:
100+       print filename
101+ 
102+The result should be 6 separate files, each with part of the log history for the
103+application::
104+ 
105+   /tmp/logging_rotatingfile_example.out
106+   /tmp/logging_rotatingfile_example.out.1
107+   /tmp/logging_rotatingfile_example.out.2
108+   /tmp/logging_rotatingfile_example.out.3
109+   /tmp/logging_rotatingfile_example.out.4
110+   /tmp/logging_rotatingfile_example.out.5
111+ 
112+The most current file is always :file:`/tmp/logging_rotatingfile_example.out`,
113+and each time it reaches the size limit it is renamed with the suffix
114+``.1``. Each of the existing backup files is renamed to increment the suffix
115+(``.1`` becomes ``.2``, etc.)  and the ``.5`` file is erased.
116+ 
117+Obviously this example sets the log length much much too small as an extreme
118+example.  You would want to set *maxBytes* to an appropriate value.
119+ 
120+Another useful feature of the logging API is the ability to produce different
121+messages at different log levels.  This allows you to instrument your code with
122+debug messages, for example, but turning the log level down so that those debug
123+messages are not written for your production system.  The default levels are
124+``CRITICAL``, ``ERROR``, ``WARNING``, ``INFO``, ``DEBUG`` and ``NOTSET``.
125+ 
126+The logger, handler, and log message call each specify a level.  The log message
127+is only emitted if the handler and logger are configured to emit messages of
128+that level or lower.  For example, if a message is ``CRITICAL``, and the logger
129+is set to ``ERROR``, the message is emitted.  If a message is a ``WARNING``, and
130+the logger is set to produce only ``ERROR``\s, the message is not emitted::
131+ 
132+   import logging
133+   import sys
134+ 
135+   LEVELS = {'debug': logging.DEBUG,
136+             'info': logging.INFO,
137+             'warning': logging.WARNING,
138+             'error': logging.ERROR,
139+             'critical': logging.CRITICAL}
140+ 
141+   if len(sys.argv) > 1:
142+       level_name = sys.argv[1]
143+       level = LEVELS.get(level_name, logging.NOTSET)
144+       logging.basicConfig(level=level)
145+ 
146+   logging.debug('This is a debug message')
147+   logging.info('This is an info message')
148+   logging.warning('This is a warning message')
149+   logging.error('This is an error message')
150+   logging.critical('This is a critical error message')
151+ 
152+Run the script with an argument like 'debug' or 'warning' to see which messages
153+show up at different levels::
154+ 
155+   $ python logging_level_example.py debug
156+   DEBUG:root:This is a debug message
157+   INFO:root:This is an info message
158+   WARNING:root:This is a warning message
159+   ERROR:root:This is an error message
160+   CRITICAL:root:This is a critical error message
161+ 
162+   $ python logging_level_example.py info
163+   INFO:root:This is an info message
164+   WARNING:root:This is a warning message
165+   ERROR:root:This is an error message
166+   CRITICAL:root:This is a critical error message
167+ 
168+You will notice that these log messages all have ``root`` embedded in them.  The
169+logging module supports a hierarchy of loggers with different names.  An easy
170+way to tell where a specific log message comes from is to use a separate logger
171+object for each of your modules.  Each new logger "inherits" the configuration
172+of its parent, and log messages sent to a logger include the name of that
173+logger.  Optionally, each logger can be configured differently, so that messages
174+from different modules are handled in different ways.  Let's look at a simple
175+example of how to log from different modules so it is easy to trace the source
176+of the message::
177+ 
178+   import logging
179+ 
180+   logging.basicConfig(level=logging.WARNING)
181+ 
182+   logger1 = logging.getLogger('package1.module1')
183+   logger2 = logging.getLogger('package2.module2')
184+ 
185+   logger1.warning('This message comes from one module')
186+   logger2.warning('And this message comes from another module')
187+ 
188+And the output::
189+ 
190+   $ python logging_modules_example.py
191+   WARNING:package1.module1:This message comes from one module
192+   WARNING:package2.module2:And this message comes from another module
193+ 
194+There are many more options for configuring logging, including different log
195+message formatting options, having messages delivered to multiple destinations,
196+and changing the configuration of a long-running application on the fly using a
197+socket interface.  All of these options are covered in depth in the library
198+module documentation.
199+ 
200+Loggers
201+^^^^^^^
202+ 
203+The logging library takes a modular approach and offers the several categories
204+of components: loggers, handlers, filters, and formatters.  Loggers expose the
205+interface that application code directly uses.  Handlers send the log records to
206+the appropriate destination. Filters provide a finer grained facility for
207+determining which log records to send on to a handler.  Formatters specify the
208+layout of the resultant log record.
209+ 
210+:class:`Logger` objects have a threefold job.  First, they expose several
211+methods to application code so that applications can log messages at runtime.
212+Second, logger objects determine which log messages to act upon based upon
213+severity (the default filtering facility) or filter objects.  Third, logger
214+objects pass along relevant log messages to all interested log handlers.
215+ 
216+The most widely used methods on logger objects fall into two categories:
217+configuration and message sending.
218+ 
219+* :meth:`Logger.setLevel` specifies the lowest-severity log message a logger
220+  will handle, where debug is the lowest built-in severity level and critical is
221+  the highest built-in severity.  For example, if the severity level is info,
222+  the logger will handle only info, warning, error, and critical messages and
223+  will ignore debug messages.
224+ 
225+* :meth:`Logger.addFilter` and :meth:`Logger.removeFilter` add and remove filter
226+  objects from the logger object.  This tutorial does not address filters.
227+ 
228+With the logger object configured, the following methods create log messages:
229+ 
230+* :meth:`Logger.debug`, :meth:`Logger.info`, :meth:`Logger.warning`,
231+  :meth:`Logger.error`, and :meth:`Logger.critical` all create log records with
232+  a message and a level that corresponds to their respective method names. The
233+  message is actually a format string, which may contain the standard string
234+  substitution syntax of :const:`%s`, :const:`%d`, :const:`%f`, and so on.  The
235+  rest of their arguments is a list of objects that correspond with the
236+  substitution fields in the message.  With regard to :const:`**kwargs`, the
237+  logging methods care only about a keyword of :const:`exc_info` and use it to
238+  determine whether to log exception information.
239+ 
240+* :meth:`Logger.exception` creates a log message similar to
241+  :meth:`Logger.error`.  The difference is that :meth:`Logger.exception` dumps a
242+  stack trace along with it.  Call this method only from an exception handler.
243+ 
244+* :meth:`Logger.log` takes a log level as an explicit argument.  This is a
245+  little more verbose for logging messages than using the log level convenience
246+  methods listed above, but this is how to log at custom log levels.
247+ 
248+:func:`getLogger` returns a reference to a logger instance with the specified
249+if it it is provided, or ``root`` if not.  The names are period-separated
250+hierarchical structures.  Multiple calls to :func:`getLogger` with the same name
251+will return a reference to the same logger object.  Loggers that are further
252+down in the hierarchical list are children of loggers higher up in the list.
253+For example, given a logger with a name of ``foo``, loggers with names of
254+``foo.bar``, ``foo.bar.baz``, and ``foo.bam`` are all children of ``foo``.
255+Child loggers propagate messages up to their parent loggers.  Because of this,
256+it is unnecessary to define and configure all the loggers an application uses.
257+It is sufficient to configure a top-level logger and create child loggers as
258+needed.
259+ 
260+ 
261+Handlers
262+^^^^^^^^
263+ 
264+:class:`Handler` objects are responsible for dispatching the appropriate log
265+messages (based on the log messages' severity) to the handler's specified
266+destination.  Logger objects can add zero or more handler objects to themselves
267+with an :func:`addHandler` method.  As an example scenario, an application may
268+want to send all log messages to a log file, all log messages of error or higher
269+to stdout, and all messages of critical to an email address.  This scenario
270+requires three individual handlers where each handler is responsible for sending
271+messages of a specific severity to a specific location.
272+ 
273+The standard library includes quite a few handler types; this tutorial uses only
274+:class:`StreamHandler` and :class:`FileHandler` in its examples.
275+ 
276+There are very few methods in a handler for application developers to concern
277+themselves with.  The only handler methods that seem relevant for application
278+developers who are using the built-in handler objects (that is, not creating
279+custom handlers) are the following configuration methods:
280+ 
281+* The :meth:`Handler.setLevel` method, just as in logger objects, specifies the
282+  lowest severity that will be dispatched to the appropriate destination.  Why
283+  are there two :func:`setLevel` methods?  The level set in the logger
284+  determines which severity of messages it will pass to its handlers.  The level
285+  set in each handler determines which messages that handler will send on.
286+  :func:`setFormatter` selects a Formatter object for this handler to use.
287+ 
288+* :func:`addFilter` and :func:`removeFilter` respectively configure and
289+  deconfigure filter objects on handlers.
290+ 
291+Application code should not directly instantiate and use handlers.  Instead, the
292+:class:`Handler` class is a base class that defines the interface that all
293+Handlers should have and establishes some default behavior that child classes
294+can use (or override).
295+ 
296+ 
297+Formatters
298+^^^^^^^^^^
299+ 
300+Formatter objects configure the final order, structure, and contents of the log
301+message.  Unlike the base :class:`logging.Handler` class, application code may
302+instantiate formatter classes, although you could likely subclass the formatter
303+if your application needs special behavior.  The constructor takes two optional
304+arguments: a message format string and a date format string.  If there is no
305+message format string, the default is to use the raw message.  If there is no
306+date format string, the default date format is::
307+ 
308+    %Y-%m-%d %H:%M:%S
309+ 
310+with the milliseconds tacked on at the end.
311+ 
312+The message format string uses ``%(<dictionary key>)s`` styled string
313+substitution; the possible keys are documented in :ref:`formatter-objects`.
314+ 
315+The following message format string will log the time in a human-readable
316+format, the severity of the message, and the contents of the message, in that
317+order::
318+ 
319+    "%(asctime)s - %(levelname)s - %(message)s"
320+ 
321+ 
322+Configuring Logging
323+^^^^^^^^^^^^^^^^^^^
324+ 
325+Programmers can configure logging either by creating loggers, handlers, and
326+formatters explicitly in a main module with the configuration methods listed
327+above (using Python code), or by creating a logging config file.  The following
328+code is an example of configuring a very simple logger, a console handler, and a
329+simple formatter in a Python module::
330+ 
331+    import logging
332+ 
333+    # create logger
334+    logger = logging.getLogger("simple_example")
335+    logger.setLevel(logging.DEBUG)
336+    # create console handler and set level to debug
337+    ch = logging.StreamHandler()
338+    ch.setLevel(logging.DEBUG)
339+    # create formatter
340+    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
341+    # add formatter to ch
342+    ch.setFormatter(formatter)
343+    # add ch to logger
344+    logger.addHandler(ch)
345+ 
346+    # "application" code
347+    logger.debug("debug message")
348+    logger.info("info message")
349+    logger.warn("warn message")
350+    logger.error("error message")
351+    logger.critical("critical message")
352+ 
353+Running this module from the command line produces the following output::
354+ 
355+    $ python simple_logging_module.py
356+    2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
357+    2005-03-19 15:10:26,620 - simple_example - INFO - info message
358+    2005-03-19 15:10:26,695 - simple_example - WARNING - warn message
359+    2005-03-19 15:10:26,697 - simple_example - ERROR - error message
360+    2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message
361+ 
362+The following Python module creates a logger, handler, and formatter nearly
363+identical to those in the example listed above, with the only difference being
364+the names of the objects::
365+ 
366+    import logging
367+    import logging.config
368+ 
369+    logging.config.fileConfig("logging.conf")
370+ 
371+    # create logger
372+    logger = logging.getLogger("simpleExample")
373+ 
374+    # "application" code
375+    logger.debug("debug message")
376+    logger.info("info message")
377+    logger.warn("warn message")
378+    logger.error("error message")
379+    logger.critical("critical message")
380+ 
381+Here is the logging.conf file::
382+ 
383+    [loggers]
384+    keys=root,simpleExample
385+ 
386+    [handlers]
387+    keys=consoleHandler
388+ 
389+    [formatters]
390+    keys=simpleFormatter
391+ 
392+    [logger_root]
393+    level=DEBUG
394+    handlers=consoleHandler
395+ 
396+    [logger_simpleExample]
397+    level=DEBUG
398+    handlers=consoleHandler
399+    qualname=simpleExample
400+    propagate=0
401+ 
402+    [handler_consoleHandler]
403+    class=StreamHandler
404+    level=DEBUG
405+    formatter=simpleFormatter
406+    args=(sys.stdout,)
407+ 
408+    [formatter_simpleFormatter]
409+    format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
410+    datefmt=
411+ 
412+The output is nearly identical to that of the non-config-file-based example::
413+ 
414+    $ python simple_logging_config.py
415+    2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
416+    2005-03-19 15:38:55,979 - simpleExample - INFO - info message
417+    2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
418+    2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
419+    2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message
420+ 
421+You can see that the config file approach has a few advantages over the Python
422+code approach, mainly separation of configuration and code and the ability of
423+noncoders to easily modify the logging properties.
424+ 
425+.. _library-config:
426+ 
427+Configuring Logging for a Library
428+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
429+ 
430+When developing a library which uses logging, some consideration needs to be
431+given to its configuration. If the using application does not use logging, and
432+library code makes logging calls, then a one-off message "No handlers could be
433+found for logger X.Y.Z" is printed to the console. This message is intended
434+to catch mistakes in logging configuration, but will confuse an application
435+developer who is not aware of logging by the library.
436+ 
437+In addition to documenting how a library uses logging, a good way to configure
438+library logging so that it does not cause a spurious message is to add a
439+handler which does nothing. This avoids the message being printed, since a
440+handler will be found: it just doesn't produce any output. If the library user
441+configures logging for application use, presumably that configuration will add
442+some handlers, and if levels are suitably configured then logging calls made
443+in library code will send output to those handlers, as normal.
444+ 
445+A do-nothing handler can be simply defined as follows::
446+ 
447+    import logging
448+ 
449+    class NullHandler(logging.Handler):
450+        def emit(self, record):
451+            pass
452+ 
453+An instance of this handler should be added to the top-level logger of the
454+logging namespace used by the library. If all logging by a library *foo* is
455+done using loggers with names matching "foo.x.y", then the code::
456+ 
457+    import logging
458+ 
459+    h = NullHandler()
460+    logging.getLogger("foo").addHandler(h)
461+ 
462+should have the desired effect. If an organisation produces a number of
463+libraries, then the logger name specified can be "orgname.foo" rather than
464+just "foo".
465+ 
466+ 
467+Logging Levels
468+--------------
38
39The numeric values of logging levels are given in the following table. These are
40primarily of interest if you want to define your own levels, and need them to
41have specific values relative to the predefined levels. If you define a level
42with the same numeric value, it overwrites the predefined value; the predefined
43name is lost.
44
45+--------------+---------------+
90In addition to the base :class:`Handler` class, many useful subclasses are
91provided:
92
93#. :class:`StreamHandler` instances send error messages to streams (file-like
94   objects).
95
96#. :class:`FileHandler` instances send error messages to disk files.
97
n98-#. :class:`BaseRotatingHandler` is the base class for handlers that rotate log
n529+#. :class:`handlers.BaseRotatingHandler` is the base class for handlers that
99-   files at a certain point. It is not meant to be  instantiated directly. Instead,
530+   rotate log files at a certain point. It is not meant to be  instantiated
100-   use :class:`RotatingFileHandler` or :class:`TimedRotatingFileHandler`.
531+   directly. Instead, use :class:`RotatingFileHandler` or
532+   :class:`TimedRotatingFileHandler`.
101
n102-#. :class:`RotatingFileHandler` instances send error messages to disk files,
n534+#. :class:`handlers.RotatingFileHandler` instances send error messages to disk files,
103   with support for maximum log file sizes and log file rotation.
104
n105-#. :class:`TimedRotatingFileHandler` instances send error messages to disk files
n537+#. :class:`handlers.TimedRotatingFileHandler` instances send error messages to disk files
106   rotating the log file at certain timed intervals.
107
n108-#. :class:`SocketHandler` instances send error messages to TCP/IP sockets.
n540+#. :class:`handlers.SocketHandler` instances send error messages to TCP/IP sockets.
109
n110-#. :class:`DatagramHandler` instances send error messages to UDP sockets.
n542+#. :class:`handlers.DatagramHandler` instances send error messages to UDP sockets.
111
n112-#. :class:`SMTPHandler` instances send error messages to a designated email
n544+#. :class:`handlers.SMTPHandler` instances send error messages to a designated email
113   address.
114
n115-#. :class:`SysLogHandler` instances send error messages to a Unix syslog daemon,
n547+#. :class:`handlers.SysLogHandler` instances send error messages to a Unix syslog daemon,
116   possibly on a remote machine.
117
n118-#. :class:`NTEventLogHandler` instances send error messages to a Windows
n550+#. :class:`handlers.NTEventLogHandler` instances send error messages to a Windows
119   NT/2000/XP event log.
120
n121-#. :class:`MemoryHandler` instances send error messages to a buffer in memory,
n553+#. :class:`handlers.MemoryHandler` instances send error messages to a buffer in memory,
122   which is flushed whenever specific criteria are met.
123
n124-#. :class:`HTTPHandler` instances send error messages to an HTTP server using
n556+#. :class:`handlers.HTTPHandler` instances send error messages to an HTTP server using
125   either ``GET`` or ``POST`` semantics.
126
n559+#. :class:`handlers.WatchedFileHandler` instances watch the file they are logging to. If
560+the file changes, it is closed and reopened using the file name. This handler
561+is only useful on Unix-like systems; Windows does not support the underlying
562+mechanism used.
563+ 
127-The :class:`StreamHandler` and :class:`FileHandler` classes are defined in the
564+The :class:`StreamHandler` and :class:`FileHandler`
128-core logging package. The other handlers are defined in a sub- module,
565+classes are defined in the core logging package. The other handlers are
129-:mod:`logging.handlers`. (There is also another sub-module,
566+defined in a sub- module, :mod:`logging.handlers`. (There is also another
130-:mod:`logging.config`, for configuration functionality.)
567+sub-module, :mod:`logging.config`, for configuration functionality.)
131
132Logged messages are formatted for presentation through instances of the
133:class:`Formatter` class. They are initialized with a format string suitable for
134use with the % operator and a dictionary.
135
136For formatting multiple messages in a batch, instances of
137:class:`BufferingFormatter` can be used. In addition to the format string (which
138is applied to each message in the batch), there is provision for header and
192   The other optional keyword argument is *extra* which can be used to pass a
193   dictionary which is used to populate the __dict__ of the LogRecord created for
194   the logging event with user-defined attributes. These custom attributes can then
195   be used as you like. For example, they could be incorporated into logged
196   messages. For example::
197
198      FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
199      logging.basicConfig(format=FORMAT)
n200-      dict = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
n637+      d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
201      logging.warning("Protocol problem: %s", "connection reset", extra=d)
202
203   would print something like  ::
204
205      2006-02-08 22:20:02,165 192.168.0.1 fbloggs  Protocol problem: connection reset
206
207   The keys in the dictionary passed in *extra* should not clash with the keys used
208   by the logging system. (See the :class:`Formatter` documentation for more
298   :class:`LogRecord` attribute dictionary, sent over a socket, and reconstituting
299   it as a :class:`LogRecord` instance at the receiving end.
300
301
302.. function:: basicConfig([**kwargs])
303
304   Does basic configuration for the logging system by creating a
305   :class:`StreamHandler` with a default :class:`Formatter` and adding it to the
n743+   root logger. The function does nothing if any handlers have been defined for
306-   root logger. The functions :func:`debug`, :func:`info`, :func:`warning`,
744+   the root logger. The functions :func:`debug`, :func:`info`, :func:`warning`,
307   :func:`error` and :func:`critical` will call :func:`basicConfig` automatically
308   if no handlers are defined for the root logger.
n747+ 
748+   This function does nothing if the root logger already has handlers configured.
309
310   .. versionchanged:: 2.4
311      Formerly, :func:`basicConfig` did not take any keyword arguments.
312
313   The following keyword arguments are supported.
314
315   +--------------+---------------------------------------------+
316   | Format       | Description                                 |
336   |              | incompatible with 'filename' - if both are  |
337   |              | present, 'stream' is ignored.               |
338   +--------------+---------------------------------------------+
339
340
341.. function:: shutdown()
342
343   Informs the logging system to perform an orderly shutdown by flushing and
n344-   closing all handlers.
n784+   closing all handlers. This should be called at application exit and no
785+   further use of the logging system should be made after this call.
345
346
347.. function:: setLoggerClass(klass)
348
349   Tells the logging system to use the class *klass* when instantiating a logger.
350   The class should define :meth:`__init__` such that only a name argument is
351   required, and the :meth:`__init__` should call :meth:`Logger.__init__`. This
352   function is typically called before any loggers are instantiated by applications
354
355
356.. seealso::
357
358   :pep:`282` - A Logging System
359      The proposal which described this feature for inclusion in the Python standard
360      library.
361
n362-   `Original Python :mod:`logging` package <http://www.red-dove.com/python_logging.html>`_
n803+   `Original Python logging package <http://www.red-dove.com/python_logging.html>`_
363      This is the original source for the :mod:`logging` package.  The version of the
364      package available from this site is suitable for use with Python 1.5.2, 2.1.x
365      and 2.2.x, which do not include the :mod:`logging` package in the standard
366      library.
367
368
369Logger Objects
370--------------
371
372Loggers have the following attributes and methods. Note that Loggers are never
373instantiated directly, but always through the module-level function
n374-:func:`logging.getLogger(name)`.
n815+``logging.getLogger(name)``.
375
376
n377-.. data:: propagate
n818+.. attribute:: Logger.propagate
378
379   If this evaluates to false, logging messages are not passed by this logger or by
380   child loggers to higher level (ancestor) loggers. The constructor sets this
381   attribute to 1.
382
383
n384-.. method:: XXX Class.setLevel(lvl)
n825+.. method:: Logger.setLevel(lvl)
385
386   Sets the threshold for this logger to *lvl*. Logging messages which are less
387   severe than *lvl* will be ignored. When a logger is created, the level is set to
388   :const:`NOTSET` (which causes all messages to be processed when the logger is
389   the root logger, or delegation to the parent when the logger is a non-root
390   logger). Note that the root logger is created with level :const:`WARNING`.
391
392   The term "delegation to the parent" means that if a logger has a level of
396   If an ancestor is found with a level other than NOTSET, then that ancestor's
397   level is treated as the effective level of the logger where the ancestor search
398   began, and is used to determine how a logging event is handled.
399
400   If the root is reached, and it has a level of NOTSET, then all messages will be
401   processed. Otherwise, the root's level will be used as the effective level.
402
403
n404-.. method:: XXX Class.isEnabledFor(lvl)
n845+.. method:: Logger.isEnabledFor(lvl)
405
406   Indicates if a message of severity *lvl* would be processed by this logger.
407   This method checks first the module-level level set by
n408-   :func:`logging.disable(lvl)` and then the logger's effective level as determined
n849+   ``logging.disable(lvl)`` and then the logger's effective level as determined
409   by :meth:`getEffectiveLevel`.
410
411
n412-.. method:: XXX Class.getEffectiveLevel()
n853+.. method:: Logger.getEffectiveLevel()
413
414   Indicates the effective level for this logger. If a value other than
415   :const:`NOTSET` has been set using :meth:`setLevel`, it is returned. Otherwise,
416   the hierarchy is traversed towards the root until a value other than
417   :const:`NOTSET` is found, and that value is returned.
418
419
n420-.. method:: XXX Class.debug(msg[, *args[, **kwargs]])
n861+.. method:: Logger.debug(msg[, *args[, **kwargs]])
421
422   Logs a message with level :const:`DEBUG` on this logger. The *msg* is the
423   message format string, and the *args* are the arguments which are merged into
424   *msg* using the string formatting operator. (Note that this means that you can
425   use keywords in the format string, together with a single dictionary argument.)
426
427   There are two keyword arguments in *kwargs* which are inspected: *exc_info*
428   which, if it does not evaluate as false, causes exception information to be
433   The other optional keyword argument is *extra* which can be used to pass a
434   dictionary which is used to populate the __dict__ of the LogRecord created for
435   the logging event with user-defined attributes. These custom attributes can then
436   be used as you like. For example, they could be incorporated into logged
437   messages. For example::
438
439      FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
440      logging.basicConfig(format=FORMAT)
n441-      dict = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
n882+      d = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
442      logger = logging.getLogger("tcpserver")
443      logger.warning("Protocol problem: %s", "connection reset", extra=d)
444
445   would print something like  ::
446
447      2006-02-08 22:20:02,165 192.168.0.1 fbloggs  Protocol problem: connection reset
448
449   The keys in the dictionary passed in *extra* should not clash with the keys used
463   context (such as remote client IP address and authenticated user name, in the
464   above example). In such circumstances, it is likely that specialized
465   :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
466
467   .. versionchanged:: 2.5
468      *extra* was added.
469
470
n471-.. method:: XXX Class.info(msg[, *args[, **kwargs]])
n912+.. method:: Logger.info(msg[, *args[, **kwargs]])
472
473   Logs a message with level :const:`INFO` on this logger. The arguments are
474   interpreted as for :meth:`debug`.
475
476
n477-.. method:: XXX Class.warning(msg[, *args[, **kwargs]])
n918+.. method:: Logger.warning(msg[, *args[, **kwargs]])
478
479   Logs a message with level :const:`WARNING` on this logger. The arguments are
480   interpreted as for :meth:`debug`.
481
482
n483-.. method:: XXX Class.error(msg[, *args[, **kwargs]])
n924+.. method:: Logger.error(msg[, *args[, **kwargs]])
484
485   Logs a message with level :const:`ERROR` on this logger. The arguments are
486   interpreted as for :meth:`debug`.
487
488
n489-.. method:: XXX Class.critical(msg[, *args[, **kwargs]])
n930+.. method:: Logger.critical(msg[, *args[, **kwargs]])
490
491   Logs a message with level :const:`CRITICAL` on this logger. The arguments are
492   interpreted as for :meth:`debug`.
493
494
n495-.. method:: XXX Class.log(lvl, msg[, *args[, **kwargs]])
n936+.. method:: Logger.log(lvl, msg[, *args[, **kwargs]])
496
497   Logs a message with integer level *lvl* on this logger. The other arguments are
498   interpreted as for :meth:`debug`.
499
500
n501-.. method:: XXX Class.exception(msg[, *args])
n942+.. method:: Logger.exception(msg[, *args])
502
503   Logs a message with level :const:`ERROR` on this logger. The arguments are
504   interpreted as for :meth:`debug`. Exception info is added to the logging
505   message. This method should only be called from an exception handler.
506
507
n508-.. method:: XXX Class.addFilter(filt)
n949+.. method:: Logger.addFilter(filt)
509
510   Adds the specified filter *filt* to this logger.
511
512
n513-.. method:: XXX Class.removeFilter(filt)
n954+.. method:: Logger.removeFilter(filt)
514
515   Removes the specified filter *filt* from this logger.
516
517
n518-.. method:: XXX Class.filter(record)
n959+.. method:: Logger.filter(record)
519
520   Applies this logger's filters to the record and returns a true value if the
521   record is to be processed.
522
523
n524-.. method:: XXX Class.addHandler(hdlr)
n965+.. method:: Logger.addHandler(hdlr)
525
526   Adds the specified handler *hdlr* to this logger.
527
528
n529-.. method:: XXX Class.removeHandler(hdlr)
n970+.. method:: Logger.removeHandler(hdlr)
530
531   Removes the specified handler *hdlr* from this logger.
532
533
n534-.. method:: XXX Class.findCaller()
n975+.. method:: Logger.findCaller()
535
n536-   Finds the caller's source filename and line number. Returns the filename and
n977+   Finds the caller's source filename and line number. Returns the filename, line
537-   line number as a 2-element tuple.
978+   number and function name as a 3-element tuple.
538
n980+   .. versionchanged:: 2.4
981+      The function name was added. In earlier versions, the filename and line number
982+      were returned as a 2-element tuple..
539
n984+ 
540-.. method:: XXX Class.handle(record)
985+.. method:: Logger.handle(record)
541
542   Handles a record by passing it to all handlers associated with this logger and
543   its ancestors (until a false value of *propagate* is found). This method is used
544   for unpickled records received from a socket, as well as those created locally.
545   Logger-level filtering is applied using :meth:`filter`.
546
547
n548-.. method:: XXX Class.makeRecord(name, lvl, fn, lno, msg, args, exc_info, func, extra)
n993+.. method:: Logger.makeRecord(name, lvl, fn, lno, msg, args, exc_info [, func, extra])
549
550   This is a factory method which can be overridden in subclasses to create
551   specialized :class:`LogRecord` instances.
552
553   .. versionchanged:: 2.5
554      *func* and *extra* were added.
555
556
603   2004-07-02 13:00:08,743 INFO Some information
604   2004-07-02 13:00:08,743 WARNING A shot across the bows
605
606This time, all messages with a severity of DEBUG or above were handled, and the
607format of the messages was also changed, and output went to the specified file
608rather than the console.
609
610Formatting uses standard Python string formatting - see section
n611-:ref:`typesseq-strings`. The format string takes the following common
n1056+:ref:`string-formatting`. The format string takes the following common
612specifiers. For a complete list of specifiers, consult the :class:`Formatter`
613documentation.
614
615+-------------------+-----------------------------------------------+
616| Format            | Description                                   |
617+===================+===============================================+
618| ``%(name)s``      | Name of the logger (logging channel).         |
619+-------------------+-----------------------------------------------+
737
738As you can see, the DEBUG message only shows up in the file. The other messages
739are sent to both destinations.
740
741This example uses console and file handlers, but you can use any number and
742combination of handlers you choose.
743
744
n1190+.. _context-info:
1191+ 
1192+Adding contextual information to your logging output
1193+----------------------------------------------------
1194+ 
1195+Sometimes you want logging output to contain contextual information in
1196+addition to the parameters passed to the logging call. For example, in a
1197+networked application, it may be desirable to log client-specific information
1198+in the log (e.g. remote client's username, or IP address). Although you could
1199+use the *extra* parameter to achieve this, it's not always convenient to pass
1200+the information in this way. While it might be tempting to create
1201+:class:`Logger` instances on a per-connection basis, this is not a good idea
1202+because these instances are not garbage collected. While this is not a problem
1203+in practice, when the number of :class:`Logger` instances is dependent on the
1204+level of granularity you want to use in logging an application, it could
1205+be hard to manage if the number of :class:`Logger` instances becomes
1206+effectively unbounded.
1207+ 
1208+An easy way in which you can pass contextual information to be output along
1209+with logging event information is to use the :class:`LoggerAdapter` class.
1210+This class is designed to look like a :class:`Logger`, so that you can call
1211+:meth:`debug`, :meth:`info`, :meth:`warning`, :meth:`error`,
1212+:meth:`exception`, :meth:`critical` and :meth:`log`. These methods have the
1213+same signatures as their counterparts in :class:`Logger`, so you can use the
1214+two types of instances interchangeably.
1215+ 
1216+When you create an instance of :class:`LoggerAdapter`, you pass it a
1217+:class:`Logger` instance and a dict-like object which contains your contextual
1218+information. When you call one of the logging methods on an instance of
1219+:class:`LoggerAdapter`, it delegates the call to the underlying instance of
1220+:class:`Logger` passed to its constructor, and arranges to pass the contextual
1221+information in the delegated call. Here's a snippet from the code of
1222+:class:`LoggerAdapter`::
1223+ 
1224+    def debug(self, msg, *args, **kwargs):
1225+        """
1226+        Delegate a debug call to the underlying logger, after adding
1227+        contextual information from this adapter instance.
1228+        """
1229+        msg, kwargs = self.process(msg, kwargs)
1230+        self.logger.debug(msg, *args, **kwargs)
1231+ 
1232+The :meth:`process` method of :class:`LoggerAdapter` is where the contextual
1233+information is added to the logging output. It's passed the message and
1234+keyword arguments of the logging call, and it passes back (potentially)
1235+modified versions of these to use in the call to the underlying logger. The
1236+default implementation of this method leaves the message alone, but inserts
1237+an "extra" key in the keyword argument whose value is the dict-like object
1238+passed to the constructor. Of course, if you had passed an "extra" keyword
1239+argument in the call to the adapter, it will be silently overwritten.
1240+ 
1241+The advantage of using "extra" is that the values in the dict-like object are
1242+merged into the :class:`LogRecord` instance's __dict__, allowing you to use
1243+customized strings with your :class:`Formatter` instances which know about
1244+the keys of the dict-like object. If you need a different method, e.g. if you
1245+want to prepend or append the contextual information to the message string,
1246+you just need to subclass :class:`LoggerAdapter` and override :meth:`process`
1247+to do what you need. Here's an example script which uses this class, which
1248+also illustrates what dict-like behaviour is needed from an arbitrary
1249+"dict-like" object for use in the constructor::
1250+ 
1251+   import logging
1252+ 
1253+   class ConnInfo:
1254+       """
1255+       An example class which shows how an arbitrary class can be used as
1256+       the 'extra' context information repository passed to a LoggerAdapter.
1257+       """
1258+ 
1259+       def __getitem__(self, name):
1260+           """
1261+           To allow this instance to look like a dict.
1262+           """
1263+           from random import choice
1264+           if name == "ip":
1265+               result = choice(["127.0.0.1", "192.168.0.1"])
1266+           elif name == "user":
1267+               result = choice(["jim", "fred", "sheila"])
1268+           else:
1269+               result = self.__dict__.get(name, "?")
1270+           return result
1271+ 
1272+       def __iter__(self):
1273+           """
1274+           To allow iteration over keys, which will be merged into
1275+           the LogRecord dict before formatting and output.
1276+           """
1277+           keys = ["ip", "user"]
1278+           keys.extend(self.__dict__.keys())
1279+           return keys.__iter__()
1280+ 
1281+   if __name__ == "__main__":
1282+       from random import choice
1283+       levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
1284+       a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"),
1285+                                  { "ip" : "123.231.231.123", "user" : "sheila" })
1286+       logging.basicConfig(level=logging.DEBUG,
1287+                           format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s")
1288+       a1.debug("A debug message")
1289+       a1.info("An info message with %s", "some parameters")
1290+       a2 = logging.LoggerAdapter(logging.getLogger("d.e.f"), ConnInfo())
1291+       for x in range(10):
1292+           lvl = choice(levels)
1293+           lvlname = logging.getLevelName(lvl)
1294+           a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters")
1295+ 
1296+When this script is run, the output should look something like this::
1297+ 
1298+   2008-01-18 14:49:54,023 a.b.c DEBUG    IP: 123.231.231.123 User: sheila   A debug message
1299+   2008-01-18 14:49:54,023 a.b.c INFO     IP: 123.231.231.123 User: sheila   An info message with some parameters
1300+   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
1301+   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
1302+   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
1303+   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
1304+   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
1305+   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
1306+   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
1307+   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
1308+   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
1309+   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
1310+ 
1311+.. versionadded:: 2.6
1312+ 
1313+The :class:`LoggerAdapter` class was not present in previous versions.
1314+ 
1315+ 
745.. _network-logging:
746
747Sending and receiving logging events across a network
748-----------------------------------------------------
749
750Let's say you want to send logging events across a network, and handle them at
751the receiving end. A simple way of doing this is attaching a
752:class:`SocketHandler` instance to the root logger at the sending end::
877---------------
878
879Handlers have the following attributes and methods. Note that :class:`Handler`
880is never instantiated directly; this class acts as a base for more useful
881subclasses. However, the :meth:`__init__` method in subclasses needs to call
882:meth:`Handler.__init__`.
883
884
n885-.. method:: XXX Class.__init__(level=NOTSET)
n1456+.. method:: Handler.__init__(level=NOTSET)
886
887   Initializes the :class:`Handler` instance by setting its level, setting the list
888   of filters to the empty list and creating a lock (using :meth:`createLock`) for
889   serializing access to an I/O mechanism.
890
891
n892-.. method:: XXX Class.createLock()
n1463+.. method:: Handler.createLock()
893
894   Initializes a thread lock which can be used to serialize access to underlying
895   I/O functionality which may not be threadsafe.
896
897
n898-.. method:: XXX Class.acquire()
n1469+.. method:: Handler.acquire()
899
900   Acquires the thread lock created with :meth:`createLock`.
901
902
n903-.. method:: XXX Class.release()
n1474+.. method:: Handler.release()
904
905   Releases the thread lock acquired with :meth:`acquire`.
906
907
n908-.. method:: XXX Class.setLevel(lvl)
n1479+.. method:: Handler.setLevel(lvl)
909
910   Sets the threshold for this handler to *lvl*. Logging messages which are less
911   severe than *lvl* will be ignored. When a handler is created, the level is set
912   to :const:`NOTSET` (which causes all messages to be processed).
913
914
n915-.. method:: XXX Class.setFormatter(form)
n1486+.. method:: Handler.setFormatter(form)
916
917   Sets the :class:`Formatter` for this handler to *form*.
918
919
n920-.. method:: XXX Class.addFilter(filt)
n1491+.. method:: Handler.addFilter(filt)
921
922   Adds the specified filter *filt* to this handler.
923
924
n925-.. method:: XXX Class.removeFilter(filt)
n1496+.. method:: Handler.removeFilter(filt)
926
927   Removes the specified filter *filt* from this handler.
928
929
n930-.. method:: XXX Class.filter(record)
n1501+.. method:: Handler.filter(record)
931
932   Applies this handler's filters to the record and returns a true value if the
933   record is to be processed.
934
935
n936-.. method:: XXX Class.flush()
n1507+.. method:: Handler.flush()
937
938   Ensure all logging output has been flushed. This version does nothing and is
939   intended to be implemented by subclasses.
940
941
n942-.. method:: XXX Class.close()
n1513+.. method:: Handler.close()
943
n944-   Tidy up any resources used by the handler. This version does nothing and is
n1515+   Tidy up any resources used by the handler. This version does no output but
945-   intended to be implemented by subclasses.
1516+   removes the handler from an internal list of handlers which is closed when
1517+   :func:`shutdown` is called. Subclasses should ensure that this gets called
1518+   from overridden :meth:`close` methods.
946
947
n948-.. method:: XXX Class.handle(record)
n1521+.. method:: Handler.handle(record)
949
950   Conditionally emits the specified logging record, depending on filters which may
951   have been added to the handler. Wraps the actual emission of the record with
952   acquisition/release of the I/O thread lock.
953
954
n955-.. method:: XXX Class.handleError(record)
n1528+.. method:: Handler.handleError(record)
956
957   This method should be called from handlers when an exception is encountered
958   during an :meth:`emit` call. By default it does nothing, which means that
959   exceptions get silently ignored. This is what is mostly wanted for a logging
960   system - most users will not care about errors in the logging system, they are
961   more interested in application errors. You could, however, replace this with a
962   custom handler if you wish. The specified record is the one which was being
963   processed when the exception occurred.
964
965
n966-.. method:: XXX Class.format(record)
n1539+.. method:: Handler.format(record)
967
968   Do formatting for a record - if a formatter is set, use it. Otherwise, use the
969   default formatter for the module.
970
971
n972-.. method:: XXX Class.emit(record)
n1545+.. method:: Handler.emit(record)
973
974   Do whatever it takes to actually log the specified logging record. This version
975   is intended to be implemented by subclasses and so raises a
976   :exc:`NotImplementedError`.
977
978
979StreamHandler
980^^^^^^^^^^^^^
981
n1555+.. module:: logging.handlers
1556+ 
982The :class:`StreamHandler` class, located in the core :mod:`logging` package,
n983-sends logging output to streams such as *sys.stdout*, *sys.stderr* or any file-
n1558+sends logging output to streams such as *sys.stdout*, *sys.stderr* or any
984-like object (or, more precisely, any object which supports :meth:`write` and
1559+file-like object (or, more precisely, any object which supports :meth:`write`
985-:meth:`flush` methods).
1560+and :meth:`flush` methods).
986
987
988.. class:: StreamHandler([strm])
989
990   Returns a new instance of the :class:`StreamHandler` class. If *strm* is
991   specified, the instance will use it for logging output; otherwise, *sys.stderr*
992   will be used.
993
994
n995-.. method:: StreamHandler.emit(record)
n1570+   .. method:: emit(record)
996
n997-   If a formatter is specified, it is used to format the record. The record is then
n1572+      If a formatter is specified, it is used to format the record. The record
998-   written to the stream with a trailing newline. If exception information is
1573+      is then written to the stream with a trailing newline. If exception
999-   present, it is formatted using :func:`traceback.print_exception` and appended to
1574+      information is present, it is formatted using
1000-   the stream.
1575+      :func:`traceback.print_exception` and appended to the stream.
1001
1002
n1003-.. method:: StreamHandler.flush()
n1578+   .. method:: flush()
1004
n1005-   Flushes the stream by calling its :meth:`flush` method. Note that the
n1580+      Flushes the stream by calling its :meth:`flush` method. Note that the
1006-   :meth:`close` method is inherited from :class:`Handler` and so does nothing, so
1581+      :meth:`close` method is inherited from :class:`Handler` and so does
1007-   an explicit :meth:`flush` call may be needed at times.
1582+      no output, so an explicit :meth:`flush` call may be needed at times.
1008
1009
1010FileHandler
1011^^^^^^^^^^^
1012
1013The :class:`FileHandler` class, located in the core :mod:`logging` package,
1014sends logging output to a disk file.  It inherits the output functionality from
1015:class:`StreamHandler`.
1016
1017
n1018-.. class:: FileHandler(filename[, mode])
n1593+.. class:: FileHandler(filename[, mode[, encoding[, delay]]])
1019
1020   Returns a new instance of the :class:`FileHandler` class. The specified file is
1021   opened and used as the stream for logging. If *mode* is not specified,
n1022-   :const:`'a'` is used. By default, the file grows indefinitely.
n1597+   :const:`'a'` is used.  If *encoding* is not *None*, it is used to open the file
1598+   with that encoding.  If *delay* is true, then file opening is deferred until the
1599+   first call to :meth:`emit`. By default, the file grows indefinitely.
1023
1024
n1025-.. method:: FileHandler.close()
n1602+   .. method:: close()
1026
n1027-   Closes the file.
n1604+      Closes the file.
1028
1029
n1030-.. method:: FileHandler.emit(record)
n1607+   .. method:: emit(record)
1031
n1032-   Outputs the record to the file.
n1609+      Outputs the record to the file.
1610+ 
1611+ 
1612+See :ref:`library-config` for more information on how to use
1613+:class:`NullHandler`.
1614+ 
1615+WatchedFileHandler
1616+^^^^^^^^^^^^^^^^^^
1617+ 
1618+.. versionadded:: 2.6
1619+ 
1620+The :class:`WatchedFileHandler` class, located in the :mod:`logging.handlers`
1621+module, is a :class:`FileHandler` which watches the file it is logging to. If
1622+the file changes, it is closed and reopened using the file name.
1623+ 
1624+A file change can happen because of usage of programs such as *newsyslog* and
1625+*logrotate* which perform log file rotation. This handler, intended for use
1626+under Unix/Linux, watches the file to see if it has changed since the last emit.
1627+(A file is deemed to have changed if its device or inode have changed.) If the
1628+file has changed, the old file stream is closed, and the file opened to get a
1629+new stream.
1630+ 
1631+This handler is not appropriate for use under Windows, because under Windows
1632+open log files cannot be moved or renamed - logging opens the files with
1633+exclusive locks - and so there is no need for such a handler. Furthermore,
1634+*ST_INO* is not supported under Windows; :func:`stat` always returns zero for
1635+this value.
1636+ 
1637+ 
1638+.. class:: WatchedFileHandler(filename[,mode[, encoding[, delay]]])
1639+ 
1640+   Returns a new instance of the :class:`WatchedFileHandler` class. The specified
1641+   file is opened and used as the stream for logging. If *mode* is not specified,
1642+   :const:`'a'` is used.  If *encoding* is not *None*, it is used to open the file
1643+   with that encoding.  If *delay* is true, then file opening is deferred until the
1644+   first call to :meth:`emit`.  By default, the file grows indefinitely.
1645+ 
1646+ 
1647+   .. method:: emit(record)
1648+ 
1649+      Outputs the record to the file, but first checks to see if the file has
1650+      changed.  If it has, the existing stream is flushed and closed and the
1651+      file opened again, before outputting the record to the file.
1033
1034
1035RotatingFileHandler
1036^^^^^^^^^^^^^^^^^^^
1037
1038The :class:`RotatingFileHandler` class, located in the :mod:`logging.handlers`
1039module, supports rotation of disk log files.
1040
1041
n1042-.. class:: RotatingFileHandler(filename[, mode[, maxBytes[, backupCount]]])
n1661+.. class:: RotatingFileHandler(filename[, mode[, maxBytes[, backupCount[, encoding[, delay]]]]])
1043
1044   Returns a new instance of the :class:`RotatingFileHandler` class. The specified
1045   file is opened and used as the stream for logging. If *mode* is not specified,
n1046-   ``'a'`` is used. By default, the file grows indefinitely.
n1665+   ``'a'`` is used.  If *encoding* is not *None*, it is used to open the file
1666+   with that encoding.  If *delay* is true, then file opening is deferred until the
1667+   first call to :meth:`emit`.  By default, the file grows indefinitely.
1047
1048   You can use the *maxBytes* and *backupCount* values to allow the file to
1049   :dfn:`rollover` at a predetermined size. When the size is about to be exceeded,
1050   the file is closed and a new file is silently opened for output. Rollover occurs
1051   whenever the current log file is nearly *maxBytes* in length; if *maxBytes* is
1052   zero, rollover never occurs.  If *backupCount* is non-zero, the system will save
1053   old log files by appending the extensions ".1", ".2" etc., to the filename. For
1054   example, with a *backupCount* of 5 and a base file name of :file:`app.log`, you
1055   would get :file:`app.log`, :file:`app.log.1`, :file:`app.log.2`, up to
1056   :file:`app.log.5`. The file being written to is always :file:`app.log`.  When
1057   this file is filled, it is closed and renamed to :file:`app.log.1`, and if files
1058   :file:`app.log.1`, :file:`app.log.2`, etc.  exist, then they are renamed to
1059   :file:`app.log.2`, :file:`app.log.3` etc.  respectively.
1060
1061
n1062-.. method:: RotatingFileHandler.doRollover()
n1683+   .. method:: doRollover()
1063
n1064-   Does a rollover, as described above.
n1685+      Does a rollover, as described above.
1065
1066
n1067-.. method:: RotatingFileHandler.emit(record)
n1688+   .. method:: emit(record)
1068
n1069-   Outputs the record to the file, catering for rollover as described previously.
n1690+      Outputs the record to the file, catering for rollover as described
1691+      previously.
1070
1071
1072TimedRotatingFileHandler
1073^^^^^^^^^^^^^^^^^^^^^^^^
1074
1075The :class:`TimedRotatingFileHandler` class, located in the
1076:mod:`logging.handlers` module, supports rotation of disk log files at certain
1077timed intervals.
1078
1079
n1080-.. class:: TimedRotatingFileHandler(filename [,when [,interval [,backupCount]]])
n1702+.. class:: TimedRotatingFileHandler(filename [,when [,interval [,backupCount[, encoding[, delay[, utc]]]]]])
1081
1082   Returns a new instance of the :class:`TimedRotatingFileHandler` class. The
1083   specified file is opened and used as the stream for logging. On rotating it also
1084   sets the filename suffix. Rotating happens based on the product of *when* and
1085   *interval*.
1086
1087   You can use the *when* to specify the type of *interval*. The list of possible
n1088-   values is, note that they are not case sensitive:
n1710+   values is below.  Note that they are not case sensitive.
1089
n1090-   +----------+-----------------------+
n1712+   +----------------+-----------------------+
1091-   | Value    | Type of interval      |
1713+   | Value          | Type of interval      |
1092-   +==========+=======================+
1714+   +================+=======================+
1093-   | S        | Seconds               |
1715+   | ``'S'``        | Seconds               |
1094-   +----------+-----------------------+
1716+   +----------------+-----------------------+
1095-   | M        | Minutes               |
1717+   | ``'M'``        | Minutes               |
1096-   +----------+-----------------------+
1718+   +----------------+-----------------------+
1097-   | H        | Hours                 |
1719+   | ``'H'``        | Hours                 |
1098-   +----------+-----------------------+
1720+   +----------------+-----------------------+
1099-   | D        | Days                  |
1721+   | ``'D'``        | Days                  |
1100-   +----------+-----------------------+
1722+   +----------------+-----------------------+
1101-   | W        | Week day (0=Monday)   |
1723+   | ``'W'``        | Week day (0=Monday)   |
1102-   +----------+-----------------------+
1724+   +----------------+-----------------------+
1103-   | midnight | Roll over at midnight |
1725+   | ``'midnight'`` | Roll over at midnight |
1104-   +----------+-----------------------+
1726+   +----------------+-----------------------+
1105
n1106-   If *backupCount* is non-zero, the system will save old log files by appending
n1728+   The system will save old log files by appending extensions to the filename.
1107-   extensions to the filename. The extensions are date-and-time based, using the
1729+   The extensions are date-and-time based, using the strftime format
1108-   strftime format ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on
1730+   ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on the
1109-   the rollover interval. At most *backupCount* files will be kept, and if more
1731+   rollover interval.
1110-   would be created when rollover occurs, the oldest one is deleted.
1732+   If the *utc* argument is true, times in UTC will be used; otherwise
1733+   local time is used.
1111
n1735+   If *backupCount* is nonzero, at most *backupCount* files
1736+   will be kept, and if more would be created when rollover occurs, the oldest
1737+   one is deleted. The deletion logic uses the interval to determine which
1738+   files to delete, so changing the interval may leave old files lying around.
1112
n1113-.. method:: TimedRotatingFileHandler.doRollover()
1114
n1741+   .. method:: doRollover()
1742+ 
1115-   Does a rollover, as described above.
1743+      Does a rollover, as described above.
1116
1117
n1118-.. method:: TimedRotatingFileHandler.emit(record)
n1746+   .. method:: emit(record)
1119
n1120-   Outputs the record to the file, catering for rollover as described above.
n1748+      Outputs the record to the file, catering for rollover as described above.
1121
1122
1123SocketHandler
1124^^^^^^^^^^^^^
1125
1126The :class:`SocketHandler` class, located in the :mod:`logging.handlers` module,
1127sends logging output to a network socket. The base class uses a TCP socket.
1128
1129
1130.. class:: SocketHandler(host, port)
1131
1132   Returns a new instance of the :class:`SocketHandler` class intended to
1133   communicate with a remote machine whose address is given by *host* and *port*.
1134
1135
n1136-.. method:: SocketHandler.close()
n1764+   .. method:: close()
1137
n1138-   Closes the socket.
n1766+      Closes the socket.
1139
1140
n1141-.. method:: SocketHandler.handleError()
n1769+   .. method:: emit()
1142
n1143- 
1144-.. method:: SocketHandler.emit()
1145- 
1146-   Pickles the record's attribute dictionary and writes it to the socket in binary
1771+      Pickles the record's attribute dictionary and writes it to the socket in
1147-   format. If there is an error with the socket, silently drops the packet. If the
1772+      binary format. If there is an error with the socket, silently drops the
1148-   connection was previously lost, re-establishes the connection. To unpickle the
1773+      packet. If the connection was previously lost, re-establishes the
1149-   record at the receiving end into a :class:`LogRecord`, use the
1774+      connection. To unpickle the record at the receiving end into a
1150-   :func:`makeLogRecord` function.
1775+      :class:`LogRecord`, use the :func:`makeLogRecord` function.
1151
1152
n1153-.. method:: SocketHandler.handleError()
n1778+   .. method:: handleError()
1154
n1155-   Handles an error which has occurred during :meth:`emit`. The most likely cause
n1780+      Handles an error which has occurred during :meth:`emit`. The most likely
1156-   is a lost connection. Closes the socket so that we can retry on the next event.
1781+      cause is a lost connection. Closes the socket so that we can retry on the
1782+      next event.
1157
1158
n1159-.. method:: SocketHandler.makeSocket()
n1785+   .. method:: makeSocket()
1160
n1161-   This is a factory method which allows subclasses to define the precise type of
n1787+      This is a factory method which allows subclasses to define the precise
1162-   socket they want. The default implementation creates a TCP socket
1788+      type of socket they want. The default implementation creates a TCP socket
1163-   (:const:`socket.SOCK_STREAM`).
1789+      (:const:`socket.SOCK_STREAM`).
1164
1165
n1166-.. method:: SocketHandler.makePickle(record)
n1792+   .. method:: makePickle(record)
1167
n1168-   Pickles the record's attribute dictionary in binary format with a length prefix,
n1794+      Pickles the record's attribute dictionary in binary format with a length
1169-   and returns it ready for transmission across the socket.
1795+      prefix, and returns it ready for transmission across the socket.
1170
1171
n1172-.. method:: SocketHandler.send(packet)
n1798+   .. method:: send(packet)
1173
n1174-   Send a pickled string *packet* to the socket. This function allows for partial
n1800+      Send a pickled string *packet* to the socket. This function allows for
1175-   sends which can happen when the network is busy.
1801+      partial sends which can happen when the network is busy.
1176
1177
1178DatagramHandler
1179^^^^^^^^^^^^^^^
1180
1181The :class:`DatagramHandler` class, located in the :mod:`logging.handlers`
1182module, inherits from :class:`SocketHandler` to support sending logging messages
1183over UDP sockets.
1184
1185
1186.. class:: DatagramHandler(host, port)
1187
1188   Returns a new instance of the :class:`DatagramHandler` class intended to
1189   communicate with a remote machine whose address is given by *host* and *port*.
1190
1191
n1192-.. method:: DatagramHandler.emit()
n1818+   .. method:: emit()
1193
n1194-   Pickles the record's attribute dictionary and writes it to the socket in binary
n1820+      Pickles the record's attribute dictionary and writes it to the socket in
1195-   format. If there is an error with the socket, silently drops the packet. To
1821+      binary format. If there is an error with the socket, silently drops the
1196-   unpickle the record at the receiving end into a :class:`LogRecord`, use the
1822+      packet. To unpickle the record at the receiving end into a
1197-   :func:`makeLogRecord` function.
1823+      :class:`LogRecord`, use the :func:`makeLogRecord` function.
1198
1199
n1200-.. method:: DatagramHandler.makeSocket()
n1826+   .. method:: makeSocket()
1201
n1202-   The factory method of :class:`SocketHandler` is here overridden to create a UDP
n1828+      The factory method of :class:`SocketHandler` is here overridden to create
1203-   socket (:const:`socket.SOCK_DGRAM`).
1829+      a UDP socket (:const:`socket.SOCK_DGRAM`).
1204
1205
n1206-.. method:: DatagramHandler.send(s)
n1832+   .. method:: send(s)
1207
n1208-   Send a pickled string to a socket.
n1834+      Send a pickled string to a socket.
1209
1210
1211SysLogHandler
1212^^^^^^^^^^^^^
1213
1214The :class:`SysLogHandler` class, located in the :mod:`logging.handlers` module,
1215supports sending logging messages to a remote or local Unix syslog.
1216
1217
1218.. class:: SysLogHandler([address[, facility]])
1219
1220   Returns a new instance of the :class:`SysLogHandler` class intended to
1221   communicate with a remote Unix machine whose address is given by *address* in
1222   the form of a ``(host, port)`` tuple.  If *address* is not specified,
n1223-   ``('localhost', 514)`` is used.  The address is used to open a UDP socket.  If
n1849+   ``('localhost', 514)`` is used.  The address is used to open a UDP socket.  An
1224-   *facility* is not specified, :const:`LOG_USER` is used.
1850+   alternative to providing a ``(host, port)`` tuple is providing an address as a
1851+   string, for example "/dev/log". In this case, a Unix domain socket is used to
1852+   send the message to the syslog. If *facility* is not specified,
1853+   :const:`LOG_USER` is used.
1225
1226
n1227-.. method:: SysLogHandler.close()
n1856+   .. method:: close()
1228
n1229-   Closes the socket to the remote host.
n1858+      Closes the socket to the remote host.
1230
1231
n1232-.. method:: SysLogHandler.emit(record)
n1861+   .. method:: emit(record)
1233
n1234-   The record is formatted, and then sent to the syslog server. If exception
n1863+      The record is formatted, and then sent to the syslog server. If exception
1235-   information is present, it is *not* sent to the server.
1864+      information is present, it is *not* sent to the server.
1236
1237
n1238-.. method:: SysLogHandler.encodePriority(facility, priority)
n1867+   .. method:: encodePriority(facility, priority)
1239
n1240-   Encodes the facility and priority into an integer. You can pass in strings or
n1869+      Encodes the facility and priority into an integer. You can pass in strings
1241-   integers - if strings are passed, internal mapping dictionaries are used to
1870+      or integers - if strings are passed, internal mapping dictionaries are
1242-   convert them to integers.
1871+      used to convert them to integers.
1243
1244
1245NTEventLogHandler
1246^^^^^^^^^^^^^^^^^
1247
1248The :class:`NTEventLogHandler` class, located in the :mod:`logging.handlers`
1249module, supports sending logging messages to a local Windows NT, Windows 2000 or
1250Windows XP event log. Before you can use it, you need Mark Hammond's Win32
1262   placeholder message definitions. Note that use of these placeholders will make
1263   your event logs big, as the entire message source is held in the log. If you
1264   want slimmer logs, you have to pass in the name of your own .dll or .exe which
1265   contains the message definitions you want to use in the event log). The
1266   *logtype* is one of ``'Application'``, ``'System'`` or ``'Security'``, and
1267   defaults to ``'Application'``.
1268
1269
n1270-.. method:: NTEventLogHandler.close()
n1899+   .. method:: close()
1271
n1272-   At this point, you can remove the application name from the registry as a source
n1901+      At this point, you can remove the application name from the registry as a
1273-   of event log entries. However, if you do this, you will not be able to see the
1902+      source of event log entries. However, if you do this, you will not be able
1274-   events as you intended in the Event Log Viewer - it needs to be able to access
1903+      to see the events as you intended in the Event Log Viewer - it needs to be
1275-   the registry to get the .dll name. The current version does not do this (in fact
1904+      able to access the registry to get the .dll name. The current version does
1276-   it doesn't do anything).
1905+      not do this.
1277
1278
n1279-.. method:: NTEventLogHandler.emit(record)
n1908+   .. method:: emit(record)
1280
n1281-   Determines the message ID, event category and event type, and then logs the
n1910+      Determines the message ID, event category and event type, and then logs
1282-   message in the NT event log.
1911+      the message in the NT event log.
1283
1284
n1285-.. method:: NTEventLogHandler.getEventCategory(record)
n1914+   .. method:: getEventCategory(record)
1286
n1287-   Returns the event category for the record. Override this if you want to specify
n1916+      Returns the event category for the record. Override this if you want to
1288-   your own categories. This version returns 0.
1917+      specify your own categories. This version returns 0.
1289
1290
n1291-.. method:: NTEventLogHandler.getEventType(record)
n1920+   .. method:: getEventType(record)
1292
n1293-   Returns the event type for the record. Override this if you want to specify your
n1922+      Returns the event type for the record. Override this if you want to
1294-   own types. This version does a mapping using the handler's typemap attribute,
1923+      specify your own types. This version does a mapping using the handler's
1295-   which is set up in :meth:`__init__` to a dictionary which contains mappings for
1924+      typemap attribute, which is set up in :meth:`__init__` to a dictionary
1296-   :const:`DEBUG`, :const:`INFO`, :const:`WARNING`, :const:`ERROR` and
1925+      which contains mappings for :const:`DEBUG`, :const:`INFO`,
1297-   :const:`CRITICAL`. If you are using your own levels, you will either need to
1926+      :const:`WARNING`, :const:`ERROR` and :const:`CRITICAL`. If you are using
1298-   override this method or place a suitable dictionary in the handler's *typemap*
1927+      your own levels, you will either need to override this method or place a
1299-   attribute.
1928+      suitable dictionary in the handler's *typemap* attribute.
1300
1301
n1302-.. method:: NTEventLogHandler.getMessageID(record)
n1931+   .. method:: getMessageID(record)
1303
n1304-   Returns the message ID for the record. If you are using your own messages, you
n1933+      Returns the message ID for the record. If you are using your own messages,
1305-   could do this by having the *msg* passed to the logger being an ID rather than a
1934+      you could do this by having the *msg* passed to the logger being an ID
1306-   format string. Then, in here, you could use a dictionary lookup to get the
1935+      rather than a format string. Then, in here, you could use a dictionary
1307-   message ID. This version returns 1, which is the base message ID in
1936+      lookup to get the message ID. This version returns 1, which is the base
1308-   :file:`win32service.pyd`.
1937+      message ID in :file:`win32service.pyd`.
1309
1310
1311SMTPHandler
1312^^^^^^^^^^^
1313
1314The :class:`SMTPHandler` class, located in the :mod:`logging.handlers` module,
1315supports sending logging messages to an email address via SMTP.
1316
1317
n1318-.. class:: SMTPHandler(mailhost, fromaddr, toaddrs, subject)
n1947+.. class:: SMTPHandler(mailhost, fromaddr, toaddrs, subject[, credentials])
1319
1320   Returns a new instance of the :class:`SMTPHandler` class. The instance is
1321   initialized with the from and to addresses and subject line of the email. The
1322   *toaddrs* should be a list of strings. To specify a non-standard SMTP port, use
1323   the (host, port) tuple format for the *mailhost* argument. If you use a string,
n1324-   the standard SMTP port is used.
n1953+   the standard SMTP port is used. If your SMTP server requires authentication, you
1954+   can specify a (username, password) tuple for the *credentials* argument.
1325
n1956+   .. versionchanged:: 2.6
1957+      *credentials* was added.
1326
n1959+ 
1327-.. method:: SMTPHandler.emit(record)
1960+   .. method:: emit(record)
1328
n1329-   Formats the record and sends it to the specified addressees.
n1962+      Formats the record and sends it to the specified addressees.
1330
1331
n1332-.. method:: SMTPHandler.getSubject(record)
n1965+   .. method:: getSubject(record)
1333
n1334-   If you want to specify a subject line which is record-dependent, override this
n1967+      If you want to specify a subject line which is record-dependent, override
1335-   method.
1968+      this method.
1336
1337
1338MemoryHandler
1339^^^^^^^^^^^^^
1340
1341The :class:`MemoryHandler` class, located in the :mod:`logging.handlers` module,
1342supports buffering of logging records in memory, periodically flushing them to a
1343:dfn:`target` handler. Flushing occurs whenever the buffer is full, or when an
1350should, then :meth:`flush` is expected to do the needful.
1351
1352
1353.. class:: BufferingHandler(capacity)
1354
1355   Initializes the handler with a buffer of the specified capacity.
1356
1357
n1358-.. method:: BufferingHandler.emit(record)
n1991+   .. method:: emit(record)
1359
n1360-   Appends the record to the buffer. If :meth:`shouldFlush` returns true, calls
n1993+      Appends the record to the buffer. If :meth:`shouldFlush` returns true,
1361-   :meth:`flush` to process the buffer.
1994+      calls :meth:`flush` to process the buffer.
1362
1363
n1364-.. method:: BufferingHandler.flush()
n1997+   .. method:: flush()
1365
n1366-   You can override this to implement custom flushing behavior. This version just
n1999+      You can override this to implement custom flushing behavior. This version
1367-   zaps the buffer to empty.
2000+      just zaps the buffer to empty.
1368
1369
n1370-.. method:: BufferingHandler.shouldFlush(record)
n2003+   .. method:: shouldFlush(record)
1371
n1372-   Returns true if the buffer is up to capacity. This method can be overridden to
n2005+      Returns true if the buffer is up to capacity. This method can be
1373-   implement custom flushing strategies.
2006+      overridden to implement custom flushing strategies.
1374
1375
1376.. class:: MemoryHandler(capacity[, flushLevel [, target]])
1377
1378   Returns a new instance of the :class:`MemoryHandler` class. The instance is
1379   initialized with a buffer size of *capacity*. If *flushLevel* is not specified,
1380   :const:`ERROR` is used. If no *target* is specified, the target will need to be
1381   set using :meth:`setTarget` before this handler does anything useful.
1382
1383
n1384-.. method:: MemoryHandler.close()
n2017+   .. method:: close()
1385
n1386-   Calls :meth:`flush`, sets the target to :const:`None` and clears the buffer.
n2019+      Calls :meth:`flush`, sets the target to :const:`None` and clears the
2020+      buffer.
1387
1388
n1389-.. method:: MemoryHandler.flush()
n2023+   .. method:: flush()
1390
n1391-   For a :class:`MemoryHandler`, flushing means just sending the buffered records
n2025+      For a :class:`MemoryHandler`, flushing means just sending the buffered
1392-   to the target, if there is one. Override if you want different behavior.
2026+      records to the target, if there is one. Override if you want different
2027+      behavior.
1393
1394
n1395-.. method:: MemoryHandler.setTarget(target)
n2030+   .. method:: setTarget(target)
1396
n1397-   Sets the target handler for this handler.
n2032+      Sets the target handler for this handler.
1398
1399
n1400-.. method:: MemoryHandler.shouldFlush(record)
n2035+   .. method:: shouldFlush(record)
1401
n1402-   Checks for buffer full or a record at the *flushLevel* or higher.
n2037+      Checks for buffer full or a record at the *flushLevel* or higher.
1403
1404
1405HTTPHandler
1406^^^^^^^^^^^
1407
1408The :class:`HTTPHandler` class, located in the :mod:`logging.handlers` module,
1409supports sending logging messages to a Web server, using either ``GET`` or
1410``POST`` semantics.
1413.. class:: HTTPHandler(host, url[, method])
1414
1415   Returns a new instance of the :class:`HTTPHandler` class. The instance is
1416   initialized with a host address, url and HTTP method. The *host* can be of the
1417   form ``host:port``, should you need to use a specific port number. If no
1418   *method* is specified, ``GET`` is used.
1419
1420
n1421-.. method:: HTTPHandler.emit(record)
n2056+   .. method:: emit(record)
1422
n1423-   Sends the record to the Web server as an URL-encoded dictionary.
n2058+      Sends the record to the Web server as an URL-encoded dictionary.
1424
n2060+ 
2061+.. _formatter-objects:
1425
1426Formatter Objects
1427-----------------
n2065+ 
2066+.. currentmodule:: logging
1428
1429:class:`Formatter`\ s have the following attributes and methods. They are
1430responsible for converting a :class:`LogRecord` to (usually) a string which can
1431be interpreted by either a human or an external system. The base
1432:class:`Formatter` allows a formatting string to be specified. If none is
1433supplied, the default value of ``'%(message)s'`` is used.
1434
1435A Formatter can be initialized with a format string which makes use of knowledge
1436of the :class:`LogRecord` attributes - such as the default value mentioned above
1437making use of the fact that the user's message and arguments are pre-formatted
1438into a :class:`LogRecord`'s *message* attribute.  This format string contains
n1439-standard python %-style mapping keys. See section :ref:`typesseq-strings`,
n2078+standard python %-style mapping keys. See section :ref:`string-formatting`
1440-"String Formatting Operations," for more information on string formatting.
2079+for more information on string formatting.
1441
1442Currently, the useful mapping keys in a :class:`LogRecord` are:
1443
n1444-+--------------------+-----------------------------------------------+
n2083++-------------------------+-----------------------------------------------+
1445-| Format             | Description                                   |
2084+| Format                  | Description                                   |
1446-+====================+===============================================+
2085++=========================+===============================================+
1447-| ``%(name)s``       | Name of the logger (logging channel).         |
2086+| ``%(name)s``            | Name of the logger (logging channel).         |
1448-+--------------------+-----------------------------------------------+
2087++-------------------------+-----------------------------------------------+
1449-| ``%(levelno)s``    | Numeric logging level for the message         |
2088+| ``%(levelno)s``         | Numeric logging level for the message         |
1450-|                    | (:const:`DEBUG`, :const:`INFO`,               |
2089+|                         | (:const:`DEBUG`, :const:`INFO`,               |
1451-|                    | :const:`WARNING`, :const:`ERROR`,             |
2090+|                         | :const:`WARNING`, :const:`ERROR`,             |
1452-|                    | :const:`CRITICAL`).                           |
2091+|                         | :const:`CRITICAL`).                           |
1453-+--------------------+-----------------------------------------------+
2092++-------------------------+-----------------------------------------------+
1454-| ``%(levelname)s``  | Text logging level for the message            |
2093+| ``%(levelname)s``       | Text logging level for the message            |
1455-|                    | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``,      |
2094+|                         | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``,      |
1456-|                    | ``'ERROR'``, ``'CRITICAL'``).                 |
2095+|                         | ``'ERROR'``, ``'CRITICAL'``).                 |
1457-+--------------------+-----------------------------------------------+
2096++-------------------------+-----------------------------------------------+
1458-| ``%(pathname)s``   | Full pathname of the source file where the    |
2097+| ``%(pathname)s``        | Full pathname of the source file where the    |
1459-|                    | logging call was issued (if available).       |
2098+|                         | logging call was issued (if available).       |
1460-+--------------------+-----------------------------------------------+
2099++-------------------------+-----------------------------------------------+
1461-| ``%(filename)s``   | Filename portion of pathname.                 |
2100+| ``%(filename)s``        | Filename portion of pathname.                 |
1462-+--------------------+-----------------------------------------------+
2101++-------------------------+-----------------------------------------------+
1463-| ``%(module)s``     | Module (name portion of filename).            |
2102+| ``%(module)s``          | Module (name portion of filename).            |
1464-+--------------------+-----------------------------------------------+
2103++-------------------------+-----------------------------------------------+
1465-| ``%(funcName)s``   | Name of function containing the logging call. |
2104+| ``%(funcName)s``        | Name of function containing the logging call. |
1466-+--------------------+-----------------------------------------------+
2105++-------------------------+-----------------------------------------------+
1467-| ``%(lineno)d``     | Source line number where the logging call was |
2106+| ``%(lineno)d``          | Source line number where the logging call was |
1468-|                    | issued (if available).                        |
2107+|                         | issued (if available).                        |
1469-+--------------------+-----------------------------------------------+
2108++-------------------------+-----------------------------------------------+
1470-| ``%(created)f``    | Time when the :class:`LogRecord` was created  |
2109+| ``%(created)f``         | Time when the :class:`LogRecord` was created  |
1471-|                    | (as returned by :func:`time.time`).           |
2110+|                         | (as returned by :func:`time.time`).           |
1472-+--------------------+-----------------------------------------------+
2111++-------------------------+-----------------------------------------------+
1473-| ``%(asctime)s``    | Human-readable time when the                  |
2112+| ``%(relativeCreated)d`` | Time in milliseconds when the LogRecord was   |
1474-|                    | :class:`LogRecord` was created.  By default   |
2113+|                         | created, relative to the time the logging     |
1475-|                    | this is of the form "2003-07-08 16:49:45,896" |
2114+|                         | module was loaded.                            |
1476-|                    | (the numbers after the comma are millisecond  |
1477-|                    | portion of the time).                         |
1478-+--------------------+-----------------------------------------------+
2115++-------------------------+-----------------------------------------------+
1479-| ``%(msecs)d``      | Millisecond portion of the time when the      |
2116+| ``%(asctime)s``         | Human-readable time when the                  |
1480-|                    | :class:`LogRecord` was created.               |
2117+|                         | :class:`LogRecord` was created.  By default   |
2118+|                         | this is of the form "2003-07-08 16:49:45,896" |
2119+|                         | (the numbers after the comma are millisecond  |
2120+|                         | portion of the time).                         |
1481-+--------------------+-----------------------------------------------+
2121++-------------------------+-----------------------------------------------+
1482-| ``%(thread)d``     | Thread ID (if available).                     |
2122+| ``%(msecs)d``           | Millisecond portion of the time when the      |
2123+|                         | :class:`LogRecord` was created.               |
1483-+--------------------+-----------------------------------------------+
2124++-------------------------+-----------------------------------------------+
1484-| ``%(threadName)s`` | Thread name (if available).                   |
2125+| ``%(thread)d``          | Thread ID (if available).                     |
1485-+--------------------+-----------------------------------------------+
2126++-------------------------+-----------------------------------------------+
1486-| ``%(process)d``    | Process ID (if available).                    |
2127+| ``%(threadName)s``      Thread name (if available).                   |
1487-+--------------------+-----------------------------------------------+
2128++-------------------------+-----------------------------------------------+
1488-| ``%(message)s``    | The logged message, computed as ``msg %       |
2129+| ``%(process)d``         | Process ID (if available).                    |
1489-|                    | args``.                                       |
1490-+--------------------+-----------------------------------------------+
2130++-------------------------+-----------------------------------------------+
2131+| ``%(message)s``         | The logged message, computed as ``msg %       |
2132+|                         | args``.                                       |
2133++-------------------------+-----------------------------------------------+
1491
1492.. versionchanged:: 2.5
1493   *funcName* was added.
1494
1495
1496.. class:: Formatter([fmt[, datefmt]])
1497
1498   Returns a new instance of the :class:`Formatter` class. The instance is
1499   initialized with a format string for the message as a whole, as well as a format
1500   string for the date/time portion of a message. If no *fmt* is specified,
1501   ``'%(message)s'`` is used. If no *datefmt* is specified, the ISO8601 date format
1502   is used.
1503
1504
n1505-.. method:: Formatter.format(record)
n2148+   .. method:: format(record)
1506
n1507-   The record's attribute dictionary is used as the operand to a string formatting
n2150+      The record's attribute dictionary is used as the operand to a string
1508-   operation. Returns the resulting string. Before formatting the dictionary, a
2151+      formatting operation. Returns the resulting string. Before formatting the
1509-   couple of preparatory steps are carried out. The *message* attribute of the
2152+      dictionary, a couple of preparatory steps are carried out. The *message*
1510-   record is computed using *msg* % *args*. If the formatting string contains
2153+      attribute of the record is computed using *msg* % *args*. If the
1511-   ``'(asctime)'``, :meth:`formatTime` is called to format the event time. If there
2154+      formatting string contains ``'(asctime)'``, :meth:`formatTime` is called
1512-   is exception information, it is formatted using :meth:`formatException` and
2155+      to format the event time. If there is exception information, it is
1513-   appended to the message.
2156+      formatted using :meth:`formatException` and appended to the message. Note
2157+      that the formatted exception information is cached in attribute
2158+      *exc_text*. This is useful because the exception information can be
2159+      pickled and sent across the wire, but you should be careful if you have
2160+      more than one :class:`Formatter` subclass which customizes the formatting
2161+      of exception information. In this case, you will have to clear the cached
2162+      value after a formatter has done its formatting, so that the next
2163+      formatter to handle the event doesn't use the cached value but
2164+      recalculates it afresh.
1514
1515
n1516-.. method:: Formatter.formatTime(record[, datefmt])
n2167+   .. method:: formatTime(record[, datefmt])
1517
n1518-   This method should be called from :meth:`format` by a formatter which wants to
n2169+      This method should be called from :meth:`format` by a formatter which
1519-   make use of a formatted time. This method can be overridden in formatters to
2170+      wants to make use of a formatted time. This method can be overridden in
1520-   provide for any specific requirement, but the basic behavior is as follows: if
2171+      formatters to provide for any specific requirement, but the basic behavior
1521-   *datefmt* (a string) is specified, it is used with :func:`time.strftime` to
2172+      is as follows: if *datefmt* (a string) is specified, it is used with
1522-   format the creation time of the record. Otherwise, the ISO8601 format is used.
2173+      :func:`time.strftime` to format the creation time of the
1523-   The resulting string is returned.
2174+      record. Otherwise, the ISO8601 format is used.  The resulting string is
2175+      returned.
1524
1525
n1526-.. method:: Formatter.formatException(exc_info)
n2178+   .. method:: formatException(exc_info)
1527
n1528-   Formats the specified exception information (a standard exception tuple as
n2180+      Formats the specified exception information (a standard exception tuple as
1529-   returned by :func:`sys.exc_info`) as a string. This default implementation just
2181+      returned by :func:`sys.exc_info`) as a string. This default implementation
1530-   uses :func:`traceback.print_exception`. The resulting string is returned.
2182+      just uses :func:`traceback.print_exception`. The resulting string is
2183+      returned.
1531
1532
1533Filter Objects
1534--------------
1535
1536:class:`Filter`\ s can be used by :class:`Handler`\ s and :class:`Logger`\ s for
1537more sophisticated filtering than is provided by levels. The base filter class
1538only allows events which are below a certain point in the logger hierarchy. For
1543
1544.. class:: Filter([name])
1545
1546   Returns an instance of the :class:`Filter` class. If *name* is specified, it
1547   names a logger which, together with its children, will have its events allowed
1548   through the filter. If no name is specified, allows every event.
1549
1550
n1551-.. method:: Filter.filter(record)
n2204+   .. method:: filter(record)
1552
n1553-   Is the specified record to be logged? Returns zero for no, nonzero for yes. If
n2206+      Is the specified record to be logged? Returns zero for no, nonzero for
1554-   deemed appropriate, the record may be modified in-place by this method.
2207+      yes. If deemed appropriate, the record may be modified in-place by this
2208+      method.
1555
1556
1557LogRecord Objects
1558-----------------
1559
1560:class:`LogRecord` instances are created every time something is logged. They
1561contain all the information pertinent to the event being logged. The main
1562information passed in is in msg and args, which are combined using msg % args to
1563create the message field of the record. The record also includes information
1564such as when the record was created, the source line where the logging call was
1565made, and any exception information to be logged.
1566
1567
n1568-.. class:: LogRecord(name, lvl, pathname, lineno, msg, args, exc_info)
n2222+.. class:: LogRecord(name, lvl, pathname, lineno, msg, args, exc_info [, func])
1569
1570   Returns an instance of :class:`LogRecord` initialized with interesting
1571   information. The *name* is the logger name; *lvl* is the numeric level;
n1572-   *pathname* is the absolute pathname of the source file in which the logging call
n2226+   *pathname* is the absolute pathname of the source file in which the logging
1573-   was made; *lineno* is the line number in that file where the logging call is
2227+   call was made; *lineno* is the line number in that file where the logging
1574-   found; *msg* is the user-supplied message (a format string); *args* is the tuple
2228+   call is found; *msg* is the user-supplied message (a format string); *args*
1575-   which, together with *msg*, makes up the user message; and *exc_info* is the
2229+   is the tuple which, together with *msg*, makes up the user message; and
1576-   exception tuple obtained by calling :func:`sys.exc_info()`\ (or :const:`None`,
2230+   *exc_info* is the exception tuple obtained by calling :func:`sys.exc_info`
1577-   if no exception information is available).
2231+   (or :const:`None`, if no exception information is available). The *func* is
2232+   the name of the function from which the logging call was made. If not
2233+   specified, it defaults to ``None``.
1578
n2235+   .. versionchanged:: 2.5
2236+      *func* was added.
1579
n2238+ 
1580-.. method:: LogRecord.getMessage()
2239+   .. method:: getMessage()
1581
n1582-   Returns the message for this :class:`LogRecord` instance after merging any user-
n2241+      Returns the message for this :class:`LogRecord` instance after merging any
1583-   supplied arguments with the message.
2242+      user-supplied arguments with the message.
2243+ 
2244+ 
2245+LoggerAdapter Objects
2246+---------------------
2247+ 
2248+.. versionadded:: 2.6
2249+ 
2250+:class:`LoggerAdapter` instances are used to conveniently pass contextual
2251+information into logging calls. For a usage example , see the section on
2252+`adding contextual information to your logging output`__.
2253+ 
2254+__ context-info_
2255+ 
2256+.. class:: LoggerAdapter(logger, extra)
2257+ 
2258+  Returns an instance of :class:`LoggerAdapter` initialized with an
2259+  underlying :class:`Logger` instance and a dict-like object.
2260+ 
2261+  .. method:: process(msg, kwargs)
2262+ 
2263+    Modifies the message and/or keyword arguments passed to a logging call in
2264+    order to insert contextual information. This implementation takes the object
2265+    passed as *extra* to the constructor and adds it to *kwargs* using key
2266+    'extra'. The return value is a (*msg*, *kwargs*) tuple which has the
2267+    (possibly modified) versions of the arguments passed in.
2268+ 
2269+In addition to the above, :class:`LoggerAdapter` supports all the logging
2270+methods of :class:`Logger`, i.e. :meth:`debug`, :meth:`info`, :meth:`warning`,
2271+:meth:`error`, :meth:`exception`, :meth:`critical` and :meth:`log`. These
2272+methods have the same signatures as their counterparts in :class:`Logger`, so
2273+you can use the two types of instances interchangeably.
1584
1585
1586Thread Safety
1587-------------
1588
1589The logging module is intended to be thread-safe without any special work
1590needing to be done by its clients. It achieves this though using threading
1591locks; there is one lock to serialize access to the module's shared data, and
1595Configuration
1596-------------
1597
1598
1599.. _logging-config-api:
1600
1601Configuration functions
1602^^^^^^^^^^^^^^^^^^^^^^^
n1603- 
1604-.. % 
1605
1606The following functions configure the logging module. They are located in the
1607:mod:`logging.config` module.  Their use is optional --- you can configure the
1608logging module using these functions or by making calls to the main API (defined
1609in :mod:`logging` itself) and defining handlers which are declared either in
1610:mod:`logging` or :mod:`logging.handlers`.
1611
1612
1623.. function:: listen([port])
1624
1625   Starts up a socket server on the specified port, and listens for new
1626   configurations. If no port is specified, the module's default
1627   :const:`DEFAULT_LOGGING_CONFIG_PORT` is used. Logging configurations will be
1628   sent as a file suitable for processing by :func:`fileConfig`. Returns a
1629   :class:`Thread` instance on which you can call :meth:`start` to start the
1630   server, and which you can :meth:`join` when appropriate. To stop the server,
n1631-   call :func:`stopListening`. To send a configuration to the socket, read in the
n2319+   call :func:`stopListening`.
1632-   configuration file and send it to the socket as a string of bytes preceded by a
2320+ 
2321+   To send a configuration to the socket, read in the configuration file and
2322+   send it to the socket as a string of bytes preceded by a four-byte length
1633-   four-byte length packed in binary using struct.\ ``pack('>L', n)``.
2323+   string packed in binary using ``struct.pack('>L', n)``.
1634
1635
1636.. function:: stopListening()
1637
n1638-   Stops the listening server which was created with a call to :func:`listen`. This
n2328+   Stops the listening server which was created with a call to :func:`listen`.
1639-   is typically called before calling :meth:`join` on the return value from
2329+   This is typically called before calling :meth:`join` on the return value from
1640   :func:`listen`.
1641
1642
1643.. _logging-config-fileformat:
1644
1645Configuration file format
1646^^^^^^^^^^^^^^^^^^^^^^^^^
n1647- 
1648-.. % 
1649
1650The configuration file format understood by :func:`fileConfig` is based on
1651ConfigParser functionality. The file must contain sections called ``[loggers]``,
1652``[handlers]`` and ``[formatters]`` which identify by name the entities of each
1653type which are defined in the file. For each such entity, there is a separate
1654section which identified how that entity is configured. Thus, for a logger named
1655``log01`` in the ``[loggers]`` section, the relevant configuration details are
1656held in a section ``[logger_log01]``. Similarly, a handler called ``hand01`` in
1714   level=NOTSET
1715   formatter=form01
1716   args=(sys.stdout,)
1717
1718The ``class`` entry indicates the handler's class (as determined by :func:`eval`
1719in the ``logging`` package's namespace). The ``level`` is interpreted as for
1720loggers, and ``NOTSET`` is taken to mean "log everything".
1721
n2410+.. versionchanged:: 2.6
2411+  Added support for resolving the handler's class as a dotted module and class
2412+  name.
2413+ 
1722The ``formatter`` entry indicates the key name of the formatter for this
1723handler. If blank, a default formatter (``logging._defaultFormatter``) is used.
1724If a name is specified, it must appear in the ``[formatters]`` section and have
1725a corresponding section in the configuration file.
1726
1727The ``args`` entry, when :func:`eval`\ uated in the context of the ``logging``
1728package's namespace, is the list of arguments to the constructor for the handler
1729class. Refer to the constructors for the relevant handlers, or to the examples
1781Sections which specify formatter configuration are typified by the following. ::
1782
1783   [formatter_form01]
1784   format=F1 %(asctime)s %(levelname)s %(message)s
1785   datefmt=
1786   class=logging.Formatter
1787
1788The ``format`` entry is the overall format string, and the ``datefmt`` entry is
n1789-the :func:`strftime`\ -compatible date/time format string. If empty, the package
n2481+the :func:`strftime`\ -compatible date/time format string.  If empty, the
1790-substitutes ISO8601 format date/times, which is almost equivalent to specifying
2482+package substitutes ISO8601 format date/times, which is almost equivalent to
1791-the date format string "The ISO8601 format also specifies milliseconds, which
2483+specifying the date format string ``"%Y-%m-%d %H:%M:%S"``.  The ISO8601 format
1792-are appended to the result of using the above format string, with a comma
2484+also specifies milliseconds, which are appended to the result of using the above
1793-separator. An example time in ISO8601 format is ``2003-01-23 00:29:50,411``.
2485+format string, with a comma separator.  An example time in ISO8601 format is
1794- 
2486+``2003-01-23 00:29:50,411``.
1795-.. % Y-%m-%d %H:%M:%S".
1796
1797The ``class`` entry is optional.  It indicates the name of the formatter's class
1798(as a dotted module and class name.)  This option is useful for instantiating a
1799:class:`Formatter` subclass.  Subclasses of :class:`Formatter` can present
1800exception tracebacks in an expanded or condensed format.
1801
t2493+ 
2494+Configuration server example
2495+^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2496+ 
2497+Here is an example of a module using the logging configuration server::
2498+ 
2499+    import logging
2500+    import logging.config
2501+    import time
2502+    import os
2503+ 
2504+    # read initial config file
2505+    logging.config.fileConfig("logging.conf")
2506+ 
2507+    # create and start listener on port 9999
2508+    t = logging.config.listen(9999)
2509+    t.start()
2510+ 
2511+    logger = logging.getLogger("simpleExample")
2512+ 
2513+    try:
2514+        # loop through logging calls to see the difference
2515+        # new configurations make, until Ctrl+C is pressed
2516+        while True:
2517+            logger.debug("debug message")
2518+            logger.info("info message")
2519+            logger.warn("warn message")
2520+            logger.error("error message")
2521+            logger.critical("critical message")
2522+            time.sleep(5)
2523+    except KeyboardInterrupt:
2524+        # cleanup
2525+        logging.config.stopListening()
2526+        t.join()
2527+ 
2528+And here is a script that takes a filename and sends that file to the server,
2529+properly preceded with the binary-encoded length, as the new logging
2530+configuration::
2531+ 
2532+    #!/usr/bin/env python
2533+    import socket, sys, struct
2534+ 
2535+    data_to_send = open(sys.argv[1], "r").read()
2536+ 
2537+    HOST = 'localhost'
2538+    PORT = 9999
2539+    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
2540+    print "connecting..."
2541+    s.connect((HOST, PORT))
2542+    print "sending config..."
2543+    s.send(struct.pack(">L", len(data_to_send)))
2544+    s.send(data_to_send)
2545+    s.close()
2546+    print "complete"
2547+ 
2548+ 
2549+More examples
2550+-------------
2551+ 
2552+Multiple handlers and formatters
2553+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2554+ 
2555+Loggers are plain Python objects.  The :func:`addHandler` method has no minimum
2556+or maximum quota for the number of handlers you may add.  Sometimes it will be
2557+beneficial for an application to log all messages of all severities to a text
2558+file while simultaneously logging errors or above to the console.  To set this
2559+up, simply configure the appropriate handlers.  The logging calls in the
2560+application code will remain unchanged.  Here is a slight modification to the
2561+previous simple module-based configuration example::
2562+ 
2563+    import logging
2564+ 
2565+    logger = logging.getLogger("simple_example")
2566+    logger.setLevel(logging.DEBUG)
2567+    # create file handler which logs even debug messages
2568+    fh = logging.FileHandler("spam.log")
2569+    fh.setLevel(logging.DEBUG)
2570+    # create console handler with a higher log level
2571+    ch = logging.StreamHandler()
2572+    ch.setLevel(logging.ERROR)
2573+    # create formatter and add it to the handlers
2574+    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
2575+    ch.setFormatter(formatter)
2576+    fh.setFormatter(formatter)
2577+    # add the handlers to logger
2578+    logger.addHandler(ch)
2579+    logger.addHandler(fh)
2580+ 
2581+    # "application" code
2582+    logger.debug("debug message")
2583+    logger.info("info message")
2584+    logger.warn("warn message")
2585+    logger.error("error message")
2586+    logger.critical("critical message")
2587+ 
2588+Notice that the "application" code does not care about multiple handlers.  All
2589+that changed was the addition and configuration of a new handler named *fh*.
2590+ 
2591+The ability to create new handlers with higher- or lower-severity filters can be
2592+very helpful when writing and testing an application.  Instead of using many
2593+``print`` statements for debugging, use ``logger.debug``: Unlike the print
2594+statements, which you will have to delete or comment out later, the logger.debug
2595+statements can remain intact in the source code and remain dormant until you
2596+need them again.  At that time, the only change that needs to happen is to
2597+modify the severity level of the logger and/or handler to debug.
2598+ 
2599+ 
2600+Using logging in multiple modules
2601+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2602+ 
2603+It was mentioned above that multiple calls to
2604+``logging.getLogger('someLogger')`` return a reference to the same logger
2605+object.  This is true not only within the same module, but also across modules
2606+as long as it is in the same Python interpreter process.  It is true for
2607+references to the same object; additionally, application code can define and
2608+configure a parent logger in one module and create (but not configure) a child
2609+logger in a separate module, and all logger calls to the child will pass up to
2610+the parent.  Here is a main module::
2611+ 
2612+    import logging
2613+    import auxiliary_module
2614+ 
2615+    # create logger with "spam_application"
2616+    logger = logging.getLogger("spam_application")
2617+    logger.setLevel(logging.DEBUG)
2618+    # create file handler which logs even debug messages
2619+    fh = logging.FileHandler("spam.log")
2620+    fh.setLevel(logging.DEBUG)
2621+    # create console handler with a higher log level
2622+    ch = logging.StreamHandler()
2623+    ch.setLevel(logging.ERROR)
2624+    # create formatter and add it to the handlers
2625+    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
2626+    fh.setFormatter(formatter)
2627+    ch.setFormatter(formatter)
2628+    # add the handlers to the logger
2629+    logger.addHandler(fh)
2630+    logger.addHandler(ch)
2631+ 
2632+    logger.info("creating an instance of auxiliary_module.Auxiliary")
2633+    a = auxiliary_module.Auxiliary()
2634+    logger.info("created an instance of auxiliary_module.Auxiliary")
2635+    logger.info("calling auxiliary_module.Auxiliary.do_something")
2636+    a.do_something()
2637+    logger.info("finished auxiliary_module.Auxiliary.do_something")
2638+    logger.info("calling auxiliary_module.some_function()")
2639+    auxiliary_module.some_function()
2640+    logger.info("done with auxiliary_module.some_function()")
2641+ 
2642+Here is the auxiliary module::
2643+ 
2644+    import logging
2645+ 
2646+    # create logger
2647+    module_logger = logging.getLogger("spam_application.auxiliary")
2648+ 
2649+    class Auxiliary:
2650+        def __init__(self):
2651+            self.logger = logging.getLogger("spam_application.auxiliary.Auxiliary")
2652+            self.logger.info("creating an instance of Auxiliary")
2653+        def do_something(self):
2654+            self.logger.info("doing something")
2655+            a = 1 + 1
2656+            self.logger.info("done doing something")
2657+ 
2658+    def some_function():
2659+        module_logger.info("received a call to \"some_function\"")
2660+ 
2661+The output looks like this::
2662+ 
2663+    2005-03-23 23:47:11,663 - spam_application - INFO -
2664+       creating an instance of auxiliary_module.Auxiliary
2665+    2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
2666+       creating an instance of Auxiliary
2667+    2005-03-23 23:47:11,665 - spam_application - INFO -
2668+       created an instance of auxiliary_module.Auxiliary
2669+    2005-03-23 23:47:11,668 - spam_application - INFO -
2670+       calling auxiliary_module.Auxiliary.do_something
2671+    2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
2672+       doing something
2673+    2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
2674+       done doing something
2675+    2005-03-23 23:47:11,670 - spam_application - INFO -
2676+       finished auxiliary_module.Auxiliary.do_something
2677+    2005-03-23 23:47:11,671 - spam_application - INFO -
2678+       calling auxiliary_module.some_function()
2679+    2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
2680+       received a call to "some_function"
2681+    2005-03-23 23:47:11,673 - spam_application - INFO -
2682+       done with auxiliary_module.some_function()
2683+ 
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op