python - Multiple streamhandlers -
i trying beef logging in python scripts , grateful if share best practices me. have created little script (i should run python 3.4)
import logging import io import sys def streamhandler(stream, level, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"): ch = logging.streamhandler(stream) ch.setlevel(level) formatter = logging.formatter(format) ch.setformatter(formatter) return ch # root logger logger = logging.getlogger() stream = io.stringio() logger.addhandler(streamhandler(stream, logging.warn)) stream_error = io.stringio() logger.addhandler(streamhandler(stream_error, logging.error)) logger.addhandler(streamhandler(stream=sys.stdout, level=logging.debug)) print(logger) h in logger.handlers: print(h) print(h.level) # 'application' code # goes root logger! logging.debug('debug message') logging.info('info message') logging.warning('warn message') logging.error('error message') logging.critical('critical message') print(stream.getvalue()) print(stream_error.getvalue())
i have 3 handlers, 2 of them write io.stringio (this seems work). need simplify testing send logs via http email service. , there streamhandler console. however, logging.debug , logging.info messages ignored on console here despite setting level explicitly low enough?!
first, didn't set level on logger itself:
logger.setlevel(logging.debug)
also, define logger
calls on logging
- call on root logger. not make difference in case since didn't specify name logger, logging.getlogger()
returns root logger.
wrt/ "best practices", depends on how "complex" scripts , of course on logging needs.
for self-contained simple scripts simple use cases (single known environment, no concurrent execution, simple logging file or stderr etc), simple call logging.basicconfig()
, direct calls logging.whatever()
enough.
for more complex, it's better use distinct config file - either in ini
format or python dict (using logging.dictconfig
), split script distinct module(s) or package(s) each defining it's own named logger (with logger = logging.getlogger(__name__)
) , keep script "runner" code, ie: configure logging, import modules, parse command line args , call main function - preferably in try/except block log unhandled exception before crashing.
Comments
Post a Comment