Python Logger not working


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.


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')

The result is:

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

According to

The INFO should be logged too.

Asked By: James King



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:


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.

Answered By: abarnert

I think you might have to set the correct threshold.

Answered By: james emanon

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.


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

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

my_logger .info("Hi")
Answered By: User 10482
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.