2017-08-27T08:56:34
Logging to a File with Python
Here's how I set up logging where:
- Log files rotate nightly (at midnight).
- We keep 10 total log files (as history).
import logging
import os
# Set up logging
logger = logging.getLogger(__file__)
handler_kwargs = {
'filename': os.path.join(base_dir, 'file.log'),
'when': 'midnight',
'backupCount': 10
}
handler = handlers.TimedRotatingFileHandler(**handler_kwargs)
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
# Now log something
logger.info('Log something informative.')
logger.warning('Log a warning.')
logger.error('Log an error.')
logger.critical('Log a critical error.')
More examples and configurations: https://docs.python.org/2.7/library/logging.html