In all my
previous posts, I defined loggers, handlers, and formatters explicitly using
Python code. It is not always good approach. One better ways is create a
logging config file and reading it using the fileConfig() function.
logging.conf
[loggers] keys=root,simpleExample [handlers] keys=consoleHandler [formatters] keys=simpleFormatter [logger_root] level=DEBUG handlers=consoleHandler [logger_simpleExample] level=DEBUG handlers=consoleHandler qualname=simpleExample propagate=0 [handler_consoleHandler] class=StreamHandler level=DEBUG formatter=simpleFormatter args=(sys.stdout,) [formatter_simpleFormatter] format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
import logging import logging.config logging.config.fileConfig('/Users/harikrishna_gurram/logging.conf') # create logger logger = logging.getLogger(__name__) def logMessages(): logger.debug('debug message') logger.info('info message') logger.warn('warn message') logger.error('error message') logger.critical('critical message') if(__name__=="__main__"): logMessages()
Run above
program, you will get following messages.
2015-10-24 13:50:46,807 - __main__ - DEBUG - debug message 2015-10-24 13:50:46,808 - __main__ - INFO - info message 2015-10-24 13:50:46,808 - __main__ - WARNING - warn message 2015-10-24 13:50:46,808 - __main__ - ERROR - error message 2015-10-24 13:50:46,808 - __main__ - CRITICAL - critical message
logging.config.fileConfig(fname, defaults=None,
disable_existing_loggers=True)
‘fileConfig’
method reads configuration from configuration file. ‘disable_existing_loggers’ is enabled by default, so all the
existing loggers before calling this function are disabled. To enable existing
loggers set ‘disable_existing_loggers’ to
false.
No comments:
Post a Comment