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