0

I'm trying to setup a logger with 2 handlers, i'm setting the handlers levels, and also the logger level, the thing is that one of the handlers which has the same level as the logger is keep getting all the messages, the second one is getting the relevant messages. Here is my code:

logger = logging.getLogger('test_logger')
logger.setLevel(logging.DEBUG)
handler1 = logging.FileHandler('logger_debug.log')
handler1.setLevel(logging.DEBUG)
handler2 = logging.FileHandler('logger_error.log')
handler2.setLevel(logging.ERROR)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -  %(message)s')
handler1.setFormatter(formatter)
handler2.setFormatter(formatter)
logger.addHandler(handler1)
logger.addHandler(handler2)
logger.debug('debug message')
logger.error('error message')
logger.info('info message')
Alex Brodov
  • 3,365
  • 18
  • 43
  • 66
  • 1
    So what is your problem? The code is working fine as it seems. Or better ask: If the current behaviour is not the one you expected, _what_ do you expect? – luator Aug 11 '15 at 11:53
  • I want that each handler will get only the on type of logging level, let's say the first handler will get all the errors, and the 2nd will get all the info messages – Alex Brodov Aug 11 '15 at 12:22
  • Okay, I understand now. The `setLevel` of `FileHandler` does set a "minimum level" for messages to be logged, i.e. all messages of the specified level **or higher** are logged. That is, if you set the level to DEBUG, it will not only log debug messages but also all messages with higher level (which are actually _all_ messages). According to the answer to [this question](http://stackoverflow.com/questions/17108973/python-logging-display-only-information-from-debug-level), which is asking for the same thing, you have to implement your own handler to achieve what you want. – luator Aug 11 '15 at 13:08

0 Answers0