Using INI config with python.logger

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.

 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:

[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.

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

And in the logfile:

$ 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

Michael is a polyglot software engineer, committed to reducing complexity in systems and making them more predictable. Working with a variety of languages and tools, he shares his technical expertise to audiences all around the world at user groups and conferences. You can follow @mheap on Twitter

Thoughts on this post

Leave a comment?

Leave a Reply