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 logginglogging.config.fileConfig("log.ini")logger = logging.getLogger('sLogger')# log somethinglogger.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=DEBUGhandlers=consoleHandler[logger_sLogger]level=DEBUGhandlers=consoleHandler,fileHandlerqualname=sLoggerpropagate=0[handler_consoleHandler]class=StreamHandlerlevel=WARNINGformatter=consoleFormatterargs=(sys.stdout,)[handler_fileHandler]class=FileHandlerlevel=DEBUGformatter=fileFormatterargs=('logfile.log',)[formatter_fileFormatter]format=%(asctime)s - %(name)s - %(levelname)s - %(message)sdatefmt=[formatter_consoleFormatter]format=%(levelname)s - %(message)sdatefmt=
This config will write warning or above out to stdout
, whilst writing everything to a logfile. e.g.
bash
$ python app.pyWARNING - warn messageERROR - error messageCRITICAL - critical message
And in the logfile:
bash
$ cat logfile.log2015-11-18 15:23:39,071 - sLogger - DEBUG - debug message2015-11-18 15:23:39,071 - sLogger - INFO - info message2015-11-18 15:23:39,071 - sLogger - WARNING - warn message2015-11-18 15:23:39,071 - sLogger - ERROR - error message2015-11-18 15:23:39,071 - sLogger - CRITICAL - critical message