Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Logger not working

Tags:

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.

like image 231
James King Avatar asked Jan 14 '14 03:01

James King


People also ask

How does logger work in Python?

Logging LevelsWhen you set a logging level in Python using the standard module, you're telling the library you want to handle all events from that level on up. If you set the log level to INFO, it will include INFO, WARNING, ERROR, and CRITICAL messages. NOTSET and DEBUG messages will not be included here.

What is Logger error in Python?

Logging an exception in python with an error can be done in the logging. exception() method. This function logs a message with level ERROR on this logger. The arguments are interpreted as for debug(). Exception info is added to the logging message.

How do I view logger information in Python?

Python Logging – INFO Level To log an INFO line using Python Logging, Check if the logger has atleast a logging level of INFO. Use logging.info() method, with the message passed as argument, to print the INFO line to the console or log file.


1 Answers

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.

like image 128
abarnert Avatar answered Oct 10 '22 03:10

abarnert