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