Your browser does not support JavaScript!
Upvotes Anonymous 1 User 0

Python 3 Logging using DictConfig

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
Was this helpful?

Tags

Comments

Leave a Comment

I agree to the Terms of Service
Design © 2015, Downranked, LLC.,
Original user code contributions under MIT License