Python Logging Rotating File Handler
Configure Python logging with rotation by size and backups, per-module loggers, structured formatting, and a root-level filter guard.
Code
import logging
import logging.config
CONFIG = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': '%(asctime)s %(levelname)s %(name)s %(message)s',
'datefmt': '%Y-%m-%dT%H:%M:%S',
},
},
'handlers': {
'app_file': {
'class': 'logging.handlers.RotatingFileHandler',
'filename': 'logs/app.log',
'maxBytes': 10 * 1024 * 1024,
'backupCount': 5,
'encoding': 'utf-8',
'formatter': 'standard',
'level': 'INFO',
},
'errors_file': {
'class': 'logging.handlers.RotatingFileHandler',
'filename': 'logs/errors.log',
'maxBytes': 5 * 1024 * 1024,
'backupCount': 3,
'formatter': 'standard',
'level': 'ERROR',
},
'console': {
'class': 'logging.StreamHandler',
'formatter': 'standard',
'level': 'WARNING',
},
},
'root': {
'level': 'DEBUG',
'handlers': ['app_file', 'errors_file', 'console'],
},
}
logging.config.dictConfig(CONFIG)
logger = logging.getLogger('billing')
logger.info('invoice generated', extra={'invoice_id': 'inv-88'})
logger.warning('payment retry scheduled')
logger.error('gateway rejected settlement', exc_info=RuntimeError('timeout'))
logger.debug('this line only reaches root handlers')Report a problem with this exampleOpens a pre-filled issue on GitHub.