blob: 453fab569459f6e6e0512c809d698c1fa56f3262 [file] [log] [blame]
Vinay Sajipc63619b2010-12-19 12:56:57 +00001:mod:`logging.config` --- Logging configuration
2===============================================
3
4.. module:: logging.config
5 :synopsis: Configuration of the logging module.
6
7
8.. moduleauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
9.. sectionauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
10
Vinay Sajip01094e12010-12-19 13:41:26 +000011.. sidebar:: Important
12
13 This page contains only reference information. For tutorials,
14 please see
15
16 * :ref:`Basic Tutorial <logging-basic-tutorial>`
17 * :ref:`Advanced Tutorial <logging-advanced-tutorial>`
18 * :ref:`Logging Cookbook <logging-cookbook>`
19
Vinay Sajip31b862d2013-09-05 23:01:07 +010020**Source code:** :source:`Lib/logging/config.py`
21
22--------------
23
Vinay Sajip01094e12010-12-19 13:41:26 +000024This section describes the API for configuring the logging module.
Vinay Sajipc63619b2010-12-19 12:56:57 +000025
26.. _logging-config-api:
27
28Configuration functions
29^^^^^^^^^^^^^^^^^^^^^^^
30
31The following functions configure the logging module. They are located in the
32:mod:`logging.config` module. Their use is optional --- you can configure the
33logging module using these functions or by making calls to the main API (defined
34in :mod:`logging` itself) and defining handlers which are declared either in
35:mod:`logging` or :mod:`logging.handlers`.
36
37.. function:: dictConfig(config)
38
39 Takes the logging configuration from a dictionary. The contents of
40 this dictionary are described in :ref:`logging-config-dictschema`
41 below.
42
43 If an error is encountered during configuration, this function will
44 raise a :exc:`ValueError`, :exc:`TypeError`, :exc:`AttributeError`
45 or :exc:`ImportError` with a suitably descriptive message. The
46 following is a (possibly incomplete) list of conditions which will
47 raise an error:
48
49 * A ``level`` which is not a string or which is a string not
50 corresponding to an actual logging level.
51 * A ``propagate`` value which is not a boolean.
52 * An id which does not have a corresponding destination.
53 * A non-existent handler id found during an incremental call.
54 * An invalid logger name.
55 * Inability to resolve to an internal or external object.
56
57 Parsing is performed by the :class:`DictConfigurator` class, whose
58 constructor is passed the dictionary used for configuration, and
59 has a :meth:`configure` method. The :mod:`logging.config` module
60 has a callable attribute :attr:`dictConfigClass`
61 which is initially set to :class:`DictConfigurator`.
62 You can replace the value of :attr:`dictConfigClass` with a
63 suitable implementation of your own.
64
65 :func:`dictConfig` calls :attr:`dictConfigClass` passing
66 the specified dictionary, and then calls the :meth:`configure` method on
67 the returned object to put the configuration into effect::
68
69 def dictConfig(config):
70 dictConfigClass(config).configure()
71
72 For example, a subclass of :class:`DictConfigurator` could call
73 ``DictConfigurator.__init__()`` in its own :meth:`__init__()`, then
74 set up custom prefixes which would be usable in the subsequent
75 :meth:`configure` call. :attr:`dictConfigClass` would be bound to
76 this new subclass, and then :func:`dictConfig` could be called exactly as
77 in the default, uncustomized state.
78
Vinay Sajip1a90f9c2011-01-27 19:14:16 +000079 .. versionadded:: 3.2
80
Vinay Sajipf97255f2011-04-19 13:56:39 +010081.. function:: fileConfig(fname, defaults=None, disable_existing_loggers=True)
Vinay Sajipc63619b2010-12-19 12:56:57 +000082
Vinay Sajipf97255f2011-04-19 13:56:39 +010083 Reads the logging configuration from a :mod:`configparser`\-format file
Vinay Sajip6068b6c2014-02-04 16:28:07 +000084 named *fname*. The format of the file should be as described in
85 :ref:`logging-config-fileformat`. This function can be called several times
86 from an application, allowing an end user to select from various pre-canned
Vinay Sajipc63619b2010-12-19 12:56:57 +000087 configurations (if the developer provides a mechanism to present the choices
Vinay Sajipf97255f2011-04-19 13:56:39 +010088 and load the chosen configuration).
89
90 :param defaults: Defaults to be passed to the ConfigParser can be specified
91 in this argument.
92
93 :param disable_existing_loggers: If specified as ``False``, loggers which
94 exist when this call is made are left
95 alone. The default is ``True`` because this
96 enables old behaviour in a backward-
97 compatible way. This behaviour is to
98 disable any existing loggers unless they or
99 their ancestors are explicitly named in the
100 logging configuration.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000101
102
103.. function:: listen(port=DEFAULT_LOGGING_CONFIG_PORT)
104
105 Starts up a socket server on the specified port, and listens for new
106 configurations. If no port is specified, the module's default
107 :const:`DEFAULT_LOGGING_CONFIG_PORT` is used. Logging configurations will be
108 sent as a file suitable for processing by :func:`fileConfig`. Returns a
Vinay Sajip67f39772013-08-17 00:39:42 +0100109 :class:`~threading.Thread` instance on which you can call
110 :meth:`~threading.Thread.start` to start the server, and which you can
111 :meth:`~threading.Thread.join` when appropriate. To stop the server,
Vinay Sajipc63619b2010-12-19 12:56:57 +0000112 call :func:`stopListening`.
113
114 To send a configuration to the socket, read in the configuration file and
115 send it to the socket as a string of bytes preceded by a four-byte length
116 string packed in binary using ``struct.pack('>L', n)``.
117
Vinay Sajip393e23f2012-07-25 19:19:25 +0100118 .. note:: Because portions of the configuration are passed through
119 :func:`eval`, use of this function may open its users to a security risk.
120 While the function only binds to a socket on ``localhost``, and so does
121 not accept connections from remote machines, there are scenarios where
122 untrusted code could be run under the account of the process which calls
123 :func:`listen`. Specifically, if the process calling :func:`listen` runs
124 on a multi-user machine where users cannot trust each other, then a
125 malicious user could arrange to run essentially arbitrary code in a
126 victim user's process, simply by connecting to the victim's
127 :func:`listen` socket and sending a configuration which runs whatever
128 code the attacker wants to have executed in the victim's process. This is
129 especially easy to do if the default port is used, but not hard even if a
130 different port is used).
Vinay Sajipc63619b2010-12-19 12:56:57 +0000131
132.. function:: stopListening()
133
134 Stops the listening server which was created with a call to :func:`listen`.
135 This is typically called before calling :meth:`join` on the return value from
136 :func:`listen`.
137
138
139.. _logging-config-dictschema:
140
141Configuration dictionary schema
142^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
143
144Describing a logging configuration requires listing the various
145objects to create and the connections between them; for example, you
146may create a handler named 'console' and then say that the logger
147named 'startup' will send its messages to the 'console' handler.
148These objects aren't limited to those provided by the :mod:`logging`
149module because you might write your own formatter or handler class.
150The parameters to these classes may also need to include external
151objects such as ``sys.stderr``. The syntax for describing these
152objects and connections is defined in :ref:`logging-config-dict-connections`
153below.
154
155Dictionary Schema Details
156"""""""""""""""""""""""""
157
158The dictionary passed to :func:`dictConfig` must contain the following
159keys:
160
161* *version* - to be set to an integer value representing the schema
162 version. The only valid value at present is 1, but having this key
163 allows the schema to evolve while still preserving backwards
164 compatibility.
165
166All other keys are optional, but if present they will be interpreted
167as described below. In all cases below where a 'configuring dict' is
168mentioned, it will be checked for the special ``'()'`` key to see if a
169custom instantiation is required. If so, the mechanism described in
170:ref:`logging-config-dict-userdef` below is used to create an instance;
171otherwise, the context is used to determine what to instantiate.
172
173* *formatters* - the corresponding value will be a dict in which each
174 key is a formatter id and each value is a dict describing how to
Vinay Sajip67f39772013-08-17 00:39:42 +0100175 configure the corresponding :class:`~logging.Formatter` instance.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000176
177 The configuring dict is searched for keys ``format`` and ``datefmt``
178 (with defaults of ``None``) and these are used to construct a
Vinay Sajip67f39772013-08-17 00:39:42 +0100179 :class:`~logging.Formatter` instance.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000180
181* *filters* - the corresponding value will be a dict in which each key
182 is a filter id and each value is a dict describing how to configure
183 the corresponding Filter instance.
184
185 The configuring dict is searched for the key ``name`` (defaulting to the
186 empty string) and this is used to construct a :class:`logging.Filter`
187 instance.
188
189* *handlers* - the corresponding value will be a dict in which each
190 key is a handler id and each value is a dict describing how to
191 configure the corresponding Handler instance.
192
193 The configuring dict is searched for the following keys:
194
195 * ``class`` (mandatory). This is the fully qualified name of the
196 handler class.
197
198 * ``level`` (optional). The level of the handler.
199
200 * ``formatter`` (optional). The id of the formatter for this
201 handler.
202
203 * ``filters`` (optional). A list of ids of the filters for this
204 handler.
205
206 All *other* keys are passed through as keyword arguments to the
207 handler's constructor. For example, given the snippet::
208
209 handlers:
210 console:
211 class : logging.StreamHandler
212 formatter: brief
213 level : INFO
214 filters: [allow_foo]
215 stream : ext://sys.stdout
216 file:
217 class : logging.handlers.RotatingFileHandler
218 formatter: precise
219 filename: logconfig.log
220 maxBytes: 1024
221 backupCount: 3
222
223 the handler with id ``console`` is instantiated as a
224 :class:`logging.StreamHandler`, using ``sys.stdout`` as the underlying
225 stream. The handler with id ``file`` is instantiated as a
226 :class:`logging.handlers.RotatingFileHandler` with the keyword arguments
227 ``filename='logconfig.log', maxBytes=1024, backupCount=3``.
228
229* *loggers* - the corresponding value will be a dict in which each key
230 is a logger name and each value is a dict describing how to
231 configure the corresponding Logger instance.
232
233 The configuring dict is searched for the following keys:
234
235 * ``level`` (optional). The level of the logger.
236
237 * ``propagate`` (optional). The propagation setting of the logger.
238
239 * ``filters`` (optional). A list of ids of the filters for this
240 logger.
241
242 * ``handlers`` (optional). A list of ids of the handlers for this
243 logger.
244
245 The specified loggers will be configured according to the level,
246 propagation, filters and handlers specified.
247
248* *root* - this will be the configuration for the root logger.
249 Processing of the configuration will be as for any logger, except
250 that the ``propagate`` setting will not be applicable.
251
252* *incremental* - whether the configuration is to be interpreted as
253 incremental to the existing configuration. This value defaults to
254 ``False``, which means that the specified configuration replaces the
255 existing configuration with the same semantics as used by the
256 existing :func:`fileConfig` API.
257
258 If the specified value is ``True``, the configuration is processed
259 as described in the section on :ref:`logging-config-dict-incremental`.
260
261* *disable_existing_loggers* - whether any existing loggers are to be
262 disabled. This setting mirrors the parameter of the same name in
263 :func:`fileConfig`. If absent, this parameter defaults to ``True``.
264 This value is ignored if *incremental* is ``True``.
265
266.. _logging-config-dict-incremental:
267
268Incremental Configuration
269"""""""""""""""""""""""""
270
271It is difficult to provide complete flexibility for incremental
272configuration. For example, because objects such as filters
273and formatters are anonymous, once a configuration is set up, it is
274not possible to refer to such anonymous objects when augmenting a
275configuration.
276
277Furthermore, there is not a compelling case for arbitrarily altering
278the object graph of loggers, handlers, filters, formatters at
279run-time, once a configuration is set up; the verbosity of loggers and
280handlers can be controlled just by setting levels (and, in the case of
281loggers, propagation flags). Changing the object graph arbitrarily in
282a safe way is problematic in a multi-threaded environment; while not
283impossible, the benefits are not worth the complexity it adds to the
284implementation.
285
286Thus, when the ``incremental`` key of a configuration dict is present
287and is ``True``, the system will completely ignore any ``formatters`` and
288``filters`` entries, and process only the ``level``
289settings in the ``handlers`` entries, and the ``level`` and
290``propagate`` settings in the ``loggers`` and ``root`` entries.
291
292Using a value in the configuration dict lets configurations to be sent
293over the wire as pickled dicts to a socket listener. Thus, the logging
294verbosity of a long-running application can be altered over time with
295no need to stop and restart the application.
296
297.. _logging-config-dict-connections:
298
299Object connections
300""""""""""""""""""
301
302The schema describes a set of logging objects - loggers,
303handlers, formatters, filters - which are connected to each other in
304an object graph. Thus, the schema needs to represent connections
305between the objects. For example, say that, once configured, a
306particular logger has attached to it a particular handler. For the
307purposes of this discussion, we can say that the logger represents the
308source, and the handler the destination, of a connection between the
309two. Of course in the configured objects this is represented by the
310logger holding a reference to the handler. In the configuration dict,
311this is done by giving each destination object an id which identifies
312it unambiguously, and then using the id in the source object's
313configuration to indicate that a connection exists between the source
314and the destination object with that id.
315
316So, for example, consider the following YAML snippet::
317
318 formatters:
319 brief:
320 # configuration for formatter with id 'brief' goes here
321 precise:
322 # configuration for formatter with id 'precise' goes here
323 handlers:
324 h1: #This is an id
325 # configuration of handler with id 'h1' goes here
326 formatter: brief
327 h2: #This is another id
328 # configuration of handler with id 'h2' goes here
329 formatter: precise
330 loggers:
331 foo.bar.baz:
332 # other configuration for logger 'foo.bar.baz'
333 handlers: [h1, h2]
334
335(Note: YAML used here because it's a little more readable than the
336equivalent Python source form for the dictionary.)
337
338The ids for loggers are the logger names which would be used
339programmatically to obtain a reference to those loggers, e.g.
340``foo.bar.baz``. The ids for Formatters and Filters can be any string
341value (such as ``brief``, ``precise`` above) and they are transient,
342in that they are only meaningful for processing the configuration
343dictionary and used to determine connections between objects, and are
344not persisted anywhere when the configuration call is complete.
345
346The above snippet indicates that logger named ``foo.bar.baz`` should
347have two handlers attached to it, which are described by the handler
348ids ``h1`` and ``h2``. The formatter for ``h1`` is that described by id
349``brief``, and the formatter for ``h2`` is that described by id
350``precise``.
351
352
353.. _logging-config-dict-userdef:
354
355User-defined objects
356""""""""""""""""""""
357
358The schema supports user-defined objects for handlers, filters and
359formatters. (Loggers do not need to have different types for
360different instances, so there is no support in this configuration
361schema for user-defined logger classes.)
362
363Objects to be configured are described by dictionaries
364which detail their configuration. In some places, the logging system
365will be able to infer from the context how an object is to be
366instantiated, but when a user-defined object is to be instantiated,
367the system will not know how to do this. In order to provide complete
368flexibility for user-defined object instantiation, the user needs
369to provide a 'factory' - a callable which is called with a
370configuration dictionary and which returns the instantiated object.
371This is signalled by an absolute import path to the factory being
372made available under the special key ``'()'``. Here's a concrete
373example::
374
375 formatters:
376 brief:
377 format: '%(message)s'
378 default:
379 format: '%(asctime)s %(levelname)-8s %(name)-15s %(message)s'
380 datefmt: '%Y-%m-%d %H:%M:%S'
381 custom:
382 (): my.package.customFormatterFactory
383 bar: baz
384 spam: 99.9
385 answer: 42
386
387The above YAML snippet defines three formatters. The first, with id
388``brief``, is a standard :class:`logging.Formatter` instance with the
389specified format string. The second, with id ``default``, has a
390longer format and also defines the time format explicitly, and will
391result in a :class:`logging.Formatter` initialized with those two format
392strings. Shown in Python source form, the ``brief`` and ``default``
393formatters have configuration sub-dictionaries::
394
395 {
396 'format' : '%(message)s'
397 }
398
399and::
400
401 {
402 'format' : '%(asctime)s %(levelname)-8s %(name)-15s %(message)s',
403 'datefmt' : '%Y-%m-%d %H:%M:%S'
404 }
405
406respectively, and as these dictionaries do not contain the special key
407``'()'``, the instantiation is inferred from the context: as a result,
408standard :class:`logging.Formatter` instances are created. The
409configuration sub-dictionary for the third formatter, with id
410``custom``, is::
411
412 {
413 '()' : 'my.package.customFormatterFactory',
414 'bar' : 'baz',
415 'spam' : 99.9,
416 'answer' : 42
417 }
418
419and this contains the special key ``'()'``, which means that
420user-defined instantiation is wanted. In this case, the specified
421factory callable will be used. If it is an actual callable it will be
422used directly - otherwise, if you specify a string (as in the example)
423the actual callable will be located using normal import mechanisms.
424The callable will be called with the **remaining** items in the
425configuration sub-dictionary as keyword arguments. In the above
426example, the formatter with id ``custom`` will be assumed to be
427returned by the call::
428
429 my.package.customFormatterFactory(bar='baz', spam=99.9, answer=42)
430
431The key ``'()'`` has been used as the special key because it is not a
432valid keyword parameter name, and so will not clash with the names of
433the keyword arguments used in the call. The ``'()'`` also serves as a
434mnemonic that the corresponding value is a callable.
435
436
437.. _logging-config-dict-externalobj:
438
439Access to external objects
440""""""""""""""""""""""""""
441
442There are times where a configuration needs to refer to objects
443external to the configuration, for example ``sys.stderr``. If the
444configuration dict is constructed using Python code, this is
445straightforward, but a problem arises when the configuration is
446provided via a text file (e.g. JSON, YAML). In a text file, there is
447no standard way to distinguish ``sys.stderr`` from the literal string
448``'sys.stderr'``. To facilitate this distinction, the configuration
449system looks for certain special prefixes in string values and
450treat them specially. For example, if the literal string
451``'ext://sys.stderr'`` is provided as a value in the configuration,
452then the ``ext://`` will be stripped off and the remainder of the
453value processed using normal import mechanisms.
454
455The handling of such prefixes is done in a way analogous to protocol
456handling: there is a generic mechanism to look for prefixes which
457match the regular expression ``^(?P<prefix>[a-z]+)://(?P<suffix>.*)$``
458whereby, if the ``prefix`` is recognised, the ``suffix`` is processed
459in a prefix-dependent manner and the result of the processing replaces
460the string value. If the prefix is not recognised, then the string
461value will be left as-is.
462
463
464.. _logging-config-dict-internalobj:
465
466Access to internal objects
467""""""""""""""""""""""""""
468
469As well as external objects, there is sometimes also a need to refer
470to objects in the configuration. This will be done implicitly by the
471configuration system for things that it knows about. For example, the
472string value ``'DEBUG'`` for a ``level`` in a logger or handler will
473automatically be converted to the value ``logging.DEBUG``, and the
474``handlers``, ``filters`` and ``formatter`` entries will take an
475object id and resolve to the appropriate destination object.
476
477However, a more generic mechanism is needed for user-defined
478objects which are not known to the :mod:`logging` module. For
479example, consider :class:`logging.handlers.MemoryHandler`, which takes
480a ``target`` argument which is another handler to delegate to. Since
481the system already knows about this class, then in the configuration,
482the given ``target`` just needs to be the object id of the relevant
483target handler, and the system will resolve to the handler from the
484id. If, however, a user defines a ``my.package.MyHandler`` which has
485an ``alternate`` handler, the configuration system would not know that
486the ``alternate`` referred to a handler. To cater for this, a generic
487resolution system allows the user to specify::
488
489 handlers:
490 file:
491 # configuration of file handler goes here
492
493 custom:
494 (): my.package.MyHandler
495 alternate: cfg://handlers.file
496
497The literal string ``'cfg://handlers.file'`` will be resolved in an
498analogous way to strings with the ``ext://`` prefix, but looking
499in the configuration itself rather than the import namespace. The
500mechanism allows access by dot or by index, in a similar way to
501that provided by ``str.format``. Thus, given the following snippet::
502
503 handlers:
504 email:
505 class: logging.handlers.SMTPHandler
506 mailhost: localhost
507 fromaddr: my_app@domain.tld
508 toaddrs:
509 - support_team@domain.tld
510 - dev_team@domain.tld
511 subject: Houston, we have a problem.
512
513in the configuration, the string ``'cfg://handlers'`` would resolve to
514the dict with key ``handlers``, the string ``'cfg://handlers.email``
515would resolve to the dict with key ``email`` in the ``handlers`` dict,
516and so on. The string ``'cfg://handlers.email.toaddrs[1]`` would
517resolve to ``'dev_team.domain.tld'`` and the string
518``'cfg://handlers.email.toaddrs[0]'`` would resolve to the value
519``'support_team@domain.tld'``. The ``subject`` value could be accessed
520using either ``'cfg://handlers.email.subject'`` or, equivalently,
521``'cfg://handlers.email[subject]'``. The latter form only needs to be
522used if the key contains spaces or non-alphanumeric characters. If an
523index value consists only of decimal digits, access will be attempted
524using the corresponding integer value, falling back to the string
525value if needed.
526
527Given a string ``cfg://handlers.myhandler.mykey.123``, this will
528resolve to ``config_dict['handlers']['myhandler']['mykey']['123']``.
529If the string is specified as ``cfg://handlers.myhandler.mykey[123]``,
530the system will attempt to retrieve the value from
531``config_dict['handlers']['myhandler']['mykey'][123]``, and fall back
532to ``config_dict['handlers']['myhandler']['mykey']['123']`` if that
533fails.
534
Vinay Sajip817495a2011-08-11 13:45:48 +0100535
536.. _logging-import-resolution:
537
538Import resolution and custom importers
539""""""""""""""""""""""""""""""""""""""
540
541Import resolution, by default, uses the builtin :func:`__import__` function
542to do its importing. You may want to replace this with your own importing
543mechanism: if so, you can replace the :attr:`importer` attribute of the
544:class:`DictConfigurator` or its superclass, the
545:class:`BaseConfigurator` class. However, you need to be
546careful because of the way functions are accessed from classes via
547descriptors. If you are using a Python callable to do your imports, and you
548want to define it at class level rather than instance level, you need to wrap
549it with :func:`staticmethod`. For example::
550
551 from importlib import import_module
552 from logging.config import BaseConfigurator
553
554 BaseConfigurator.importer = staticmethod(import_module)
555
556You don't need to wrap with :func:`staticmethod` if you're setting the import
557callable on a configurator *instance*.
558
559
Vinay Sajipc63619b2010-12-19 12:56:57 +0000560.. _logging-config-fileformat:
561
562Configuration file format
563^^^^^^^^^^^^^^^^^^^^^^^^^
564
565The configuration file format understood by :func:`fileConfig` is based on
566:mod:`configparser` functionality. The file must contain sections called
567``[loggers]``, ``[handlers]`` and ``[formatters]`` which identify by name the
568entities of each type which are defined in the file. For each such entity, there
569is a separate section which identifies how that entity is configured. Thus, for
570a logger named ``log01`` in the ``[loggers]`` section, the relevant
571configuration details are held in a section ``[logger_log01]``. Similarly, a
572handler called ``hand01`` in the ``[handlers]`` section will have its
573configuration held in a section called ``[handler_hand01]``, while a formatter
574called ``form01`` in the ``[formatters]`` section will have its configuration
575specified in a section called ``[formatter_form01]``. The root logger
576configuration must be specified in a section called ``[logger_root]``.
577
578Examples of these sections in the file are given below. ::
579
580 [loggers]
581 keys=root,log02,log03,log04,log05,log06,log07
582
583 [handlers]
584 keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
585
586 [formatters]
587 keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
588
589The root logger must specify a level and a list of handlers. An example of a
590root logger section is given below. ::
591
592 [logger_root]
593 level=NOTSET
594 handlers=hand01
595
596The ``level`` entry can be one of ``DEBUG, INFO, WARNING, ERROR, CRITICAL`` or
597``NOTSET``. For the root logger only, ``NOTSET`` means that all messages will be
598logged. Level values are :func:`eval`\ uated in the context of the ``logging``
599package's namespace.
600
601The ``handlers`` entry is a comma-separated list of handler names, which must
602appear in the ``[handlers]`` section. These names must appear in the
603``[handlers]`` section and have corresponding sections in the configuration
604file.
605
606For loggers other than the root logger, some additional information is required.
607This is illustrated by the following example. ::
608
609 [logger_parser]
610 level=DEBUG
611 handlers=hand01
612 propagate=1
613 qualname=compiler.parser
614
615The ``level`` and ``handlers`` entries are interpreted as for the root logger,
616except that if a non-root logger's level is specified as ``NOTSET``, the system
617consults loggers higher up the hierarchy to determine the effective level of the
618logger. The ``propagate`` entry is set to 1 to indicate that messages must
619propagate to handlers higher up the logger hierarchy from this logger, or 0 to
620indicate that messages are **not** propagated to handlers up the hierarchy. The
621``qualname`` entry is the hierarchical channel name of the logger, that is to
622say the name used by the application to get the logger.
623
624Sections which specify handler configuration are exemplified by the following.
625::
626
627 [handler_hand01]
628 class=StreamHandler
629 level=NOTSET
630 formatter=form01
631 args=(sys.stdout,)
632
633The ``class`` entry indicates the handler's class (as determined by :func:`eval`
634in the ``logging`` package's namespace). The ``level`` is interpreted as for
635loggers, and ``NOTSET`` is taken to mean 'log everything'.
636
637The ``formatter`` entry indicates the key name of the formatter for this
638handler. If blank, a default formatter (``logging._defaultFormatter``) is used.
639If a name is specified, it must appear in the ``[formatters]`` section and have
640a corresponding section in the configuration file.
641
642The ``args`` entry, when :func:`eval`\ uated in the context of the ``logging``
643package's namespace, is the list of arguments to the constructor for the handler
644class. Refer to the constructors for the relevant handlers, or to the examples
645below, to see how typical entries are constructed. ::
646
647 [handler_hand02]
648 class=FileHandler
649 level=DEBUG
650 formatter=form02
651 args=('python.log', 'w')
652
653 [handler_hand03]
654 class=handlers.SocketHandler
655 level=INFO
656 formatter=form03
657 args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
658
659 [handler_hand04]
660 class=handlers.DatagramHandler
661 level=WARN
662 formatter=form04
663 args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
664
665 [handler_hand05]
666 class=handlers.SysLogHandler
667 level=ERROR
668 formatter=form05
669 args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
670
671 [handler_hand06]
672 class=handlers.NTEventLogHandler
673 level=CRITICAL
674 formatter=form06
675 args=('Python Application', '', 'Application')
676
677 [handler_hand07]
678 class=handlers.SMTPHandler
679 level=WARN
680 formatter=form07
681 args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
682
683 [handler_hand08]
684 class=handlers.MemoryHandler
685 level=NOTSET
686 formatter=form08
687 target=
688 args=(10, ERROR)
689
690 [handler_hand09]
691 class=handlers.HTTPHandler
692 level=NOTSET
693 formatter=form09
694 args=('localhost:9022', '/log', 'GET')
695
696Sections which specify formatter configuration are typified by the following. ::
697
698 [formatter_form01]
699 format=F1 %(asctime)s %(levelname)s %(message)s
700 datefmt=
701 class=logging.Formatter
702
703The ``format`` entry is the overall format string, and the ``datefmt`` entry is
704the :func:`strftime`\ -compatible date/time format string. If empty, the
705package substitutes ISO8601 format date/times, which is almost equivalent to
706specifying the date format string ``'%Y-%m-%d %H:%M:%S'``. The ISO8601 format
707also specifies milliseconds, which are appended to the result of using the above
708format string, with a comma separator. An example time in ISO8601 format is
709``2003-01-23 00:29:50,411``.
710
711The ``class`` entry is optional. It indicates the name of the formatter's class
712(as a dotted module and class name.) This option is useful for instantiating a
Vinay Sajip67f39772013-08-17 00:39:42 +0100713:class:`~logging.Formatter` subclass. Subclasses of
714:class:`~logging.Formatter` can present exception tracebacks in an expanded or
715condensed format.
Vinay Sajipc63619b2010-12-19 12:56:57 +0000716
Vinay Sajip393e23f2012-07-25 19:19:25 +0100717.. note:: Due to the use of :func:`eval` as described above, there are
718 potential security risks which result from using the :func:`listen` to send
719 and receive configurations via sockets. The risks are limited to where
720 multiple users with no mutual trust run code on the same machine; see the
721 :func:`listen` documentation for more information.
722
Vinay Sajipc63619b2010-12-19 12:56:57 +0000723.. seealso::
724
725 Module :mod:`logging`
726 API reference for the logging module.
727
728 Module :mod:`logging.handlers`
729 Useful handlers included with the logging module.
730
731