Using INI config with python.logger

18 Nov 2015 in TIL

This is a quick one about how to configure Python's build in logging system using an ini file.

Our application needs to import logging and logging.config to be able to use ini files.

python
import logging, logging.config
# set up logging
logging.config.fileConfig("log.ini")
logger = logging.getLogger('sLogger')
# log something
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

log.ini looks like this:

ini
[loggers]
keys=root,sLogger
[handlers]
keys=consoleHandler,fileHandler
[formatters]
keys=fileFormatter,consoleFormatter
[logger_root]
level=DEBUG
handlers=consoleHandler
[logger_sLogger]
level=DEBUG
handlers=consoleHandler,fileHandler
qualname=sLogger
propagate=0
[handler_consoleHandler]
class=StreamHandler
level=WARNING
formatter=consoleFormatter
args=(sys.stdout,)
[handler_fileHandler]
class=FileHandler
level=DEBUG
formatter=fileFormatter
args=('logfile.log',)
[formatter_fileFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=
[formatter_consoleFormatter]
format=%(levelname)s - %(message)s
datefmt=

This config will write warning or above out to stdout, whilst writing everything to a logfile. e.g.

bash
$ python app.py
WARNING - warn message
ERROR - error message
CRITICAL - critical message

And in the logfile:

bash
$ cat logfile.log
2015-11-18 15:23:39,071 - sLogger - DEBUG - debug message
2015-11-18 15:23:39,071 - sLogger - INFO - info message
2015-11-18 15:23:39,071 - sLogger - WARNING - warn message
2015-11-18 15:23:39,071 - sLogger - ERROR - error message
2015-11-18 15:23:39,071 - sLogger - CRITICAL - critical message