Python - Logging from multiple modules to rotating files without printing to console -
i trying add logging medium size python project minimal disruption. log multiple modules rotating files silently (without printing messages terminal). have tried modify this example , have functionality need except 1 issue.
here how attempting configure things in main script:
import logging import logging.handlers import my_module log_file = 'logs\\logging_example_new.out' #logging.basicconfig(level=logging.debug) # define handler writes messages rotating log files. handler = logging.handlers.rotatingfilehandler(log_file, maxbytes=100000, backupcount=1) handler.setlevel(logging.debug) # set logging level. # create message formatter. formatter = logging.formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s') # tell handler use format handler.setformatter(formatter) # add handler root logger logging.getlogger('').addhandler(handler) # now, can log root logger, or other logger. first root... logging.debug('root debug message.') logging.info('root info message.') logging.warning('root warning message.') logging.error('root error message.') logging.critical('root critical message.') # use logger in module. my_module.do_something() # call function logs message.
here sample of trying in modules:
import logging def do_something(): logger = logging.getlogger(__name__) logger.debug('module debug message.') logger.info('module info message.') logger.warning('module warning message.') logger.error('module error message.') logger.critical('module critical message.')
now, here problem. messages logged rotating files silently. warning, error, , critical messages. despite setting handler.setlevel(logging.debug)
.
if uncomment logging.basicconfig(level=logging.debug)
, messages in log files messages printed terminal.
how messages above specified threshold log files without outputing them terminal?
thanks!
update: based on answer, appears calling logging.basicconfig(level=logging.debug)
automatically adds streamhandler
root logger , can remove it. when did remove leaving rotatingfilehandler
, messages no longer printed terminal. still wondering why have use logging.basicconfig(level=logging.debug)
set message level threshold, when setting handler.setlevel(logging.debug)
. if can shed little more light on these issues still appreciated.
you need call set logging level on logger well. believe default, logging level on logger logging.warning
ex.
root_logger = logging.getlogger('') root_logger.setlevel(logging.debug) # add handler root logger root_logger.addhandler(handler)
the loggers log level determines logger log (i.e messages handed handlers). handlers log level determines handle (i.e. messages output file, stream, etc). potentially have multiple handlers attached logger each handling different log level.
here's so answer explains way works
Comments
Post a Comment