Sub topic 11
Configuring logging with dictConfig
This chapter assumes you know how loggers, handlers, formatters, and levels fit together, and how records propagate up the logger hierarchy. It also assumes you can read nested dictionaries and JSON. The chapter shows how to describe all of that in one dictionary and apply it with a single call.
Why use dictConfig
Building handlers and formatters in code works for small scripts. In a larger application, setup code scatters across modules, and changing a level means editing Python. logging.config.dictConfig takes a dictionary that describes the whole setup and builds the objects for you.
This has three benefits:
- The configuration is data. You can load it from JSON or YAML and change it per environment.
- Everything is in one place, so you can see where each record goes.
- Objects refer to each other by name, which avoids ordering mistakes such as attaching a formatter to the wrong handler.
dictConfig replaces the older fileConfig, which reads INI files and cannot express filters or custom factories. Prefer dictConfig in new code.
The shape of the dictionary
The dictionary has a fixed set of top-level keys.
| Key | Required | Meaning |
|---|---|---|
| `version` | Yes | Must be the integer `1`. |
| `formatters` | No | Maps a name to formatter settings. |
| `filters` | No | Maps a name to filter settings. |
| `handlers` | No | Maps a name to handler settings. |
| `loggers` | No | Maps a logger name to its level, handlers, and `propagate` flag. |
| `root` | No | Settings for the root logger. |
| `disable_existing_loggers` | No | Defaults to `True`. See the pitfall section below. |
| `incremental` | No | Defaults to `False`. When true, only handler levels and logger levels are updated. |
Handlers refer to formatters and filters by name. Loggers refer to handlers by name.
A first complete configuration
This example uses all three kinds of component. It defines a filter that adds a request_id attribute, a console handler that writes to standard output, and a rotating file handler.
import logging
import logging.config
class RequestIdFilter(logging.Filter):
def filter(self, record):
record.request_id = "req-123"
return True
config = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"standard": {
"format": "%(asctime)s %(levelname)-8s %(request_id)s %(name)s: %(message)s",
"datefmt": "%Y-%m-%d %H:%M:%S",
}
},
"filters": {
"request_id": {"()": RequestIdFilter},
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"level": "INFO",
"formatter": "standard",
"filters": ["request_id"],
"stream": "ext://sys.stdout",
},
"file": {
"class": "logging.handlers.RotatingFileHandler",
"level": "DEBUG",
"formatter": "standard",
"filters": ["request_id"],
"filename": "app.log",
"maxBytes": 1_000_000,
"backupCount": 3,
"encoding": "utf-8",
},
},
"loggers": {
"myapp": {
"level": "DEBUG",
"handlers": ["console", "file"],
"propagate": False,
},
"myapp.db": {"level": "WARNING"},
},
"root": {"level": "WARNING", "handlers": ["console"]},
}
logging.config.dictConfig(config)
logging.getLogger("myapp").debug("File only")
logging.getLogger("myapp.web").info("Console and file")
logging.getLogger("myapp.db").info("Dropped: myapp.db is at WARNING")
logging.getLogger("myapp.db").warning("Console and file")Running this prints two lines to the console and writes three lines to app.log. Each line includes req-123.
Here is how each part works:
"class"is a dotted path to a handler class. Every other key that is not a reserved name (level,formatter,filters) is passed to the constructor as a keyword argument.filename,maxBytes, andbackupCountreachRotatingFileHandlerthis way."ext://sys.stdout"resolves an external object by import path. Without it, you would have to pass a string where the handler needs a stream."()"marks a custom factory. The value is a callable or a dotted path to one. The remaining keys in that dictionary become its arguments. Use it for filters, formatters, and handlers that the standardclasskey cannot build.myapp.dbhas no handlers of its own. Its records propagate tomyapp, which has two handlers. SettingpropagatetoFalseonmyappstops them from also reaching the root's console handler, so nothing prints twice.
Loading configuration from a file
Because the configuration is a plain dictionary, you can keep it in JSON and load it at startup.
import json
import logging.config
from pathlib import Path
def setup_logging(path="logging.json"):
with Path(path).open(encoding="utf-8") as f:
logging.config.dictConfig(json.load(f))JSON has no way to reference Python objects, so a JSON file cannot contain a class object under "()". Use a dotted-path string such as "myapp.logging_setup.RequestIdFilter" instead. YAML works the same way if you install a parser, but the standard library does not include one.
Pitfalls
Existing loggers silently go quiet
disable_existing_loggers defaults to True. Any logger that already exists when dictConfig runs and is not named in the configuration is disabled, along with its children. This happens often because module-level logger = logging.getLogger(__name__) lines run at import time, before your setup function.
import logging
import logging.config
early = logging.getLogger("early") # created before configuration
logging.config.dictConfig({
"version": 1,
"handlers": {"console": {"class": "logging.StreamHandler"}},
"root": {"level": "INFO", "handlers": ["console"]},
})
early.warning("You will not see this") # the logger is disabledSet "disable_existing_loggers": False in nearly every application. Setting it to True is only useful if you really want to silence loggers that your configuration does not mention.
Misspelled keys and names fail at configuration time
Referring to a handler or formatter name that is not defined raises ValueError. The error wraps the underlying KeyError, so read the whole message. A wrong class path raises ValueError as well. This is useful because the failure happens at startup instead of when the first record is emitted.
Calling dictConfig repeatedly
Each non-incremental call replaces the handlers on the configured loggers. It does not add to them. Calling it twice with the same dictionary is safe. It will not duplicate output the way calling addHandler twice does. Call it once, early, in the entry point of the application and not in library code.
Levels are strings, handlers are named
Level values are strings such as "INFO". Numeric values also work, but names are easier to read. A handler without a level key accepts everything. A logger without a level key inherits from its parent, as you saw in the hierarchy chapter.
A practical layout
A common structure keeps the dictionary in one module and exposes a function to apply it.
- Put the dictionary in
logging_config.pyas a module-level constant, or load it from a file. - Add a
setup_logging()function that callsdictConfig. - Call
setup_logging()once, from the program'smain()or the web framework's startup hook, before creating objects that log. - In every other module, use only
logging.getLogger(__name__)and never configure anything.
Environment-specific differences, such as DEBUG locally and WARNING in production, can be handled by editing the dictionary before the call:
import copy
import logging.config
import os
from logging_config import CONFIG
def setup_logging():
config = copy.deepcopy(CONFIG)
config["root"]["level"] = os.environ.get("LOG_LEVEL", "INFO")
logging.config.dictConfig(config)The deepcopy keeps the shared constant unchanged, so repeated calls behave consistently.
Exercise
A module has logger = logging.getLogger("billing") at the top. The application's main() later calls dictConfig with a configuration that defines only a root logger with a console handler, and it does not set disable_existing_loggers. Why does logger.error("failed") print nothing, and what is the smallest change that fixes it?
Show answer
disable_existing_loggers defaults to True. The billing logger was created at import time, before dictConfig ran, and the configuration does not name it, so dictConfig disables it. Adding "disable_existing_loggers": False to the dictionary fixes it. After that, billing records propagate to the root logger's console handler.
Exercise
A configuration defines the logger myapp with handlers ["console"] and the default propagate. The root logger also has the handler ["console"]. Every message from myapp appears twice. What are two ways to stop the duplication?
Show answer
The record is handled by the console handler on myapp and then propagates to the root logger, where the same handler runs again. Either set "propagate": False on myapp, or remove the handler from myapp and let the root logger's handler do the work. Define the handler in only one place.