Here's a full example of using DictConfig in Python 3:
import logging
import logging.config
def configure_logger(name, log_path):
logging.config.dictConfig({
'version': 1,
'formatters': {
'default': {'format': '%(asctime)s - %(levelname)s - %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S'}
},
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'default',
'stream': 'ext://sys.stdout'
},
'file': {
'level': 'DEBUG',
'class': 'logging.handlers.RotatingFileHandler',
'formatter': 'default',
'filename': log_path,
'maxBytes': 1024,
'backupCount': 3
}
},
'loggers': {
'default': {
'level': 'DEBUG',
'handlers': ['console', 'file']
}
},
'disable_existing_loggers': False
})
return logging.getLogger(name)
alog = configure_logger('default', 'log13.txt')
alog.debug('debug message!')
alog.info('info message!')
alog.error('error message')
alog.critical('critical message')
alog.warning('warning message')
This logs to both the console and a log file. Here's the output:
2014-11-04 23:57:44 - DEBUG - debug message!
2014-11-04 23:57:44 - INFO - info message!
2014-11-04 23:57:44 - ERROR - error message
2014-11-04 23:57:44 - CRITICAL - critical message
2014-11-04 23:57:44 - WARNING - warning message
The following articles were very helpful in figuring this out:
http://stackoverflow.com/questions/7507825/python-complete-example-of-dict-for-logging-config-dictconfig
http://stackoverflow.com/questions/3220284/how-to-customize-the-time-format-for-python-logging
https://docs.python.org/3/library/logging.config.html#logging.config.dictConfig
(Bits and pieces from the these articles were customized for the example above)
I took me a lot of time to find this simple and working example. Thanks a lot! Bob
Leave a comment