简体   繁体   中英

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.

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.

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.

我想你可能需要设置正确的阈值。

logger.setLevel(logging.INFO)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM