Back to results for “Logging”
Python › Logging

How do you configure logging using a dictionary via logging.config.dictConfig?

Intermediate

Answer

dictConfig accepts a nested dictionary describing formatters, handlers, loggers, and their relationships, letting you define a full logging setup declaratively (often loaded from a JSON or YAML file) rather than imperatively calling addHandler/setFormatter in code. This is the recommended way to manage complex, environment-specific logging configuration.
import logging.config

config = {
    'version': 1,
    'formatters': {'simple': {'format': '%(levelname)s: %(message)s'}},
    'handlers': {'console': {'class': 'logging.StreamHandler', 'formatter': 'simple'}},
    'root': {'handlers': ['console'], 'level': 'INFO'},
}
logging.config.dictConfig(config)
logging.info('Configured via dict')
Real-world example A Django or Flask application loads its LOGGING dict from settings, switching handlers and levels between development and production environments without code changes.

Common follow-ups: How does dictConfig differ from fileConfig?;How do you merge dictConfig with environment variables for secrets?