Reputation: 1614
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.
Upvotes: 33
Views: 59456
Reputation: 990
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
Upvotes: 17
Reputation: 11807
I think you might have to set the correct threshold.
logger.setLevel(logging.INFO)
Upvotes: 8
Reputation: 365587
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.
Upvotes: 43