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