Home > Enterprise >  Python Logging : File Handler doesn't work
Python Logging : File Handler doesn't work

Time:11-11

Here is a reproducible code snippet:

import logging

logger=logging.getLogger('test')
#create a stream handler for logging out to console.
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.ERROR)

#create a file handler for logging to file
file_handler = logging.FileHandler('logs',mode='a')
file_handler.setLevel(logging.DEBUG)

logger.addHandler(file_handler)
logger.addHandler(stream_handler)

logger.info("this is info")

I am expecting the log to appear in the file named logs however it never writes the log to that file. What am I missing here?

CodePudding user response:

When you create a logger, its logging level is NOTSET, thus it inherits its level from root logger (i.e. its parent logger), which has the logging level WARNING by default and info has a lower level so its not passed to the handlers. Try setting the logger level as well with

logger.setLevel(logging.DEBUG)

  • Related