Sub topic 11
Configuring logging with dictConfig
This chapter assumes you know loggers, handlers, formatters, levels, and propagation from the earlier chapters. logging.config.dictConfig builds all of those objects from one dictionary. The configuration then lives in one place, and you can load it from JSON or YAML.
The shape of the dictionary
The dictionary has these keys:
| Key | Purpose |
|---|---|
| `version` | Required. Must be `1`. |
| `formatters` | Named format definitions. |
| `filters` | Named filter definitions. |
| `handlers` | Named handlers. Each one refers to a formatter by name. |
| `loggers` | Settings for named loggers. Each one refers to handlers by name. |
| `root` | Settings for the root logger. |
| `disable_existing_loggers` | Defaults to `True`. |
Objects refer to each other by name. A handler says "formatter": "standard", and a logger says "handlers": ["console"].
A working configuration
This example sends INFO and above to the console and everything to a file. It also quiets one noisy logger.
import logging
import logging.config
config = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"standard": {
"format": "%(asctime)s %(levelname)-8s %(name)s: %(message)s"
}
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"formatter": "standard",
"level": "INFO",
},
"file": {
"class": "logging.FileHandler",
"formatter": "standard",
"level": "DEBUG",
"filename": "app.log",
"encoding": "utf-8",
},
},
"root": {"level": "DEBUG", "handlers": ["console", "file"]},
"loggers": {"myapp.db": {"level": "WARNING"}},
}
logging.config.dictConfig(config)
logging.getLogger("myapp").debug("File only")
logging.getLogger("myapp").info("File and console")
logging.getLogger("myapp.db").info("Dropped by the myapp.db level")Keys in a handler entry other than class, level, formatter, and filters are passed to the handler's constructor. That is how filename and encoding reach FileHandler. The same pattern works for RotatingFileHandler with maxBytes and backupCount.
Only the root logger has handlers here. The myapp loggers have none of their own, so their records propagate up to the root handlers. This is the usual design: attach handlers at the root and set levels on named loggers.
Common errors
- Missing
version.dictConfigraisesValueError. Always write"version": 1. - Unknown name. A logger that lists
"handlers": ["consol"]fails withValueError: Unable to configure handler. Check the spelling against thehandlerssection. disable_existing_loggersleft atTrue. Any logger created beforedictConfigruns, such as one made at import time withgetLogger(__name__), is silently disabled unless the config names it. Set the key toFalsein nearly every application.- Duplicate output. If you add a handler to
myappand leavepropagateasTrue, the root handler also emits the record. Set"propagate": Falseon that logger entry, or keep handlers only on the root. - Calling it repeatedly. Each call replaces handlers on the configured loggers. It is safe to call again, but do it once, at startup, from the entry point and not from library code.
Loading from a file
Because the configuration is plain data, you can keep it outside your code.
import json
import logging.config
with open("logging.json", encoding="utf-8") as f:
logging.config.dictConfig(json.load(f))Exercise
A module runs logger = logging.getLogger(__name__) at import time. The application then calls dictConfig with disable_existing_loggers omitted, and the module's log messages stop appearing. Why, and what is the fix?
Show answer
The default for disable_existing_loggers is True, so dictConfig disables every logger that already exists and is not named in the configuration. The module's logger was created before the call, so it was disabled. Add "disable_existing_loggers": False to the dictionary.