33

I try to use logging in Python to write some log, but strangely, only the error will be logged, the info will be ignored no matter whichn level I set.

code:

import logging
import logging.handlers

if __name__ == "__main__":
    logger = logging.getLogger()
    fh = logging.handlers.RotatingFileHandler('./logtest.log', maxBytes=10240, backupCount=5)
    fh.setLevel(logging.DEBUG)#no matter what level I set here
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    fh.setFormatter(formatter)
    logger.addHandler(fh)
    logger.info('INFO')
    logger.error('ERROR')

The result is:

2014-01-14 11:47:38,990 - root - ERROR - ERROR

According to http://docs.python.org/2/library/logging.html#logging-levels

The INFO should be logged too.

3 Answers 3

44

The problem is that the logger's level is still set to the default. So the logger discards the message before it even gets to the handlers. The fact that the handler would have accepted the message if it received it doesn't matter, because it never receives it.

So, just add this:

logger.setLevel(logging.INFO)

As the docs explain, the logger's default level is NOTSET, which means it checks with its parent, which is the root, which has a default of WARNING.

And you can probably leave the handler at its default of NOTSET, which means it defers to the logger's filtering.

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

3 Comments

...but the question sets it to logging.DEFAULT
This is not a solution, I might have different handlers and each one with different levels of logging. For example having a file_handler and a console_handler. Like defined in this article: realpython.com/python-logging , and not working.
I have done what the OP has done, but I also set the level and it still wouldn't log :/
18

I got a logger using logging.getLogger(__name__). I tried setting the log level to logging.INFO as mentioned in other answers, but that didn't work.

A quick check on both the created logger and its parent (root) logger showed it did not have any handlers (using hasHandler()). The documentation states that the handler should've been created upon first call to any of logging functions debug, info etc.,

The functions debug(), info(), warning(), error() and critical() will call basicConfig() automatically if no handlers are defined for the root logger.

But it did not. All I had to do was call basicConfig() manually.

Solution:

import logging
logging.basicConfig()  # Add logging level here if you plan on using logging.info() instead of my_logger as below.

my_logger = logging.getLogger(__name__)
my_logger .setLevel(logging.INFO)

my_logger .info("Hi")
INFO:__main__:Hi

Comments

8

I think you might have to set the correct threshold.

logger.setLevel(logging.INFO)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.