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