0

I am trying to usa a logger with a file handler. But irrespective of the loglevel I set to the handlers, it always has loglevel of WARNING. Below is my code.

import os
import logging

log_file = 'myapp.log'

logger = logging.getLogger(my_logger)

f_handler = logging.FileHandler(log_file)
f_handler.setLevel(logging.DEBUG)
f_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
f_handler.setFormatter(f_formatter)
logger.addHandler(f_handler)


logger.debug('this is debug message')
logger.info('this is info message')
logger.warning('this is warning message')
logger.error('this is error message')
logger.critical('this is critical message')

I see only the warning and above level messages in my file 'myapp.log'

2020-05-25 19:28:13,259 - my_logger - WARNING - this is warning message
2020-05-25 19:28:13,260 - my_logger - ERROR - this is error message
2020-05-25 19:28:13,260 - my_logger - CRITICAL - this is critical message

What am I missing?

1
  • After the line where you have instantiated the logger, that is after logger.getlogger , if you add logger.setLevel(logging.DEBUG) and just remove the handler's setlevel that is f_handler.setLevel it works . i just tried Commented May 25, 2020 at 14:17

1 Answer 1

1

You need to set the level of logger along with the handler. Handlers log the message which is equal or above both the log levels (logger level and handler level)

So setting the level of logger to DEBUG as below will let the handlers choose the level of logging for them to log

logger.setLevel(logging.DEBUG)

Note: Default level of logger is WARN

Sign up to request clarification or add additional context in comments.

4 Comments

But when I add multiple loggers with different log level each, setting at logger level wouldn't suffice, isn't it?
Sorry, I'm not sure what you mean. You can always try it out.
I would like to have file handler(log all >= debug messages) and console handler(log all >= warn messages). So this gives the flexibitliy of configuring logging level at handler rather than on whole logger
Ok, that shouldn't be a problem. You still need to set logging.DEBUG on the logger for it to even "produce" a less than WARN message. Then set the appropriate levels on the handlers (i.e. logging.DEBUG on the file handler and logging.WARN on the console handler) for them to "allow" to consume the message. Does it make sense?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.