Python
dictConfig
Learn advanced config with logging.config.dictConfig.
dictConfig
logging.config.dictConfig sets up a complex logging configuration from a dict. Handlers, formatters and loggers are defined separately; this is good for working with configuration loaded from a file.
import logging.config
config = {
"version": 1,
"formatters": {"simple": {"format": "%(levelname)s:%(message)s"}},
"handlers": {"console": {"class": "logging.StreamHandler", "formatter": "simple"}},
"loggers": {"myapp": {"handlers": ["console"], "level": "DEBUG"}},
}
logging.config.dictConfig(config)
version: 1 is always given. The dict structure lets you manage many loggers and handlers from one place.
Dict sections
The dictConfig dict has four main sections: formatters, handlers, loggers and root. Each is a dict of dicts.
config = {
"version": 1,
"formatters": {"simple": {...}},
"handlers": {"console": {...}},
"loggers": {"myapp": {...}},
}
A handler refers to a formatter by name; a logger refers to a handler by name. This makes components reusable.
Exercise Log with dictConfig
Start with import logging.config. Define a dict config: "version": 1, "formatters": {"simple": {"format": "%(levelname)s:%(message)s"}}, "handlers": {"console": {"class": "logging.StreamHandler", "formatter": "simple"}}, "loggers": {"myapp": {"handlers": ["console"], "level": "DEBUG"}}. Call logging.config.dictConfig(config). Get a logger with logger = logging.getLogger("myapp"). Also add the import logging line. Write logger.info("merhaba").
Show example solution
import logging
import logging.config
config = {
"version": 1,
"formatters": {"simple": {"format": "%(levelname)s:%(message)s"}},
"handlers": {"console": {"class": "logging.StreamHandler", "formatter": "simple"}},
"loggers": {"myapp": {"handlers": ["console"], "level": "DEBUG"}},
}
logging.config.dictConfig(config)
logger = logging.getLogger("myapp")
logger.info("merhaba")
Test yourself
-
Complete the dictConfig call
import logging.config
logging.config.____(config)
Show answer
import logging.config
logging.config.dictConfig(config)
-
What does the 'version' key do in a dictConfig dict?
- Specifies the logger name
- Specifies the configuration version
- Specifies the file path
- Specifies the level
Show answer
Specifies the configuration version — The version key specifies the configuration version; usually 1.
-
Match the dictConfig concepts
- version
- Specifies the version
- formatters
- Defines formatters
- handlers
- Defines handlers
- loggers
- Defines loggers
Next lesson: Summary - Logging