In a python script I am writing, I am trying to log events using the logging module. I have the following code to configure my logger:
ERROR_FORMAT = "%(levelname)s at %(asctime)s in %(funcName)s in %(filename) at line %(lineno)d: %(message)s"
DEBUG_FORMAT = "%(lineno)d in %(filename)s at %(asctime)s: %(message)s"
LOG_CONFIG = {'version':1,
'formatters':{'error':{'format':ERROR_FORMAT},
'debug':{'format':DEBUG_FORMAT}},
'handlers':{'console':{'class':'logging.StreamHandler',
'formatter':'debug',
'level':logging.DEBUG},
'file':{'class':'logging.FileHandler',
'filename':'/usr/local/logs/DatabaseUpdate.log',
'formatter':'error',
'level':logging.ERROR}},
'root':{'handlers':('console', 'file')}}
logging.config.dictConfig(LOG_CONFIG)
When I try to run logging.debug("Some string")
, I get no output to the console, even though this page in the docs says that logging.debug
should have the root logger output the message. Why is my program not outputting anything, and how can I fix it?
Many years later there seems to still be a usability problem with the Python logger. Here's some explanations with examples:
A common source of confusion comes from a badly initialised root logger. Consider this:
Output:
Depending on your runtime environment and logging levels, the first log line (before basic config) might not show up anywhere.
For anyone here that wants a super-simple answer: just set the level you want displayed. At the top of all my scripts I just put:
Then to display anything at or above that level:
It is a hierarchical set of five levels so that logs will display at the level you set, or higher. So if you want to display an error you could use
logging.error("The plumbus is broken")
.The levels, in increasing order of severity, are
DEBUG
,INFO
,WARNING
,ERROR
, andCRITICAL
. The default setting isWARNING
.This is a good article containing this information expressed better than my answer:
https://www.digitalocean.com/community/tutorials/how-to-use-logging-in-python-3
Maybe try this? It seems the problem is solved after remove all the handlers in my case.
The default logging level is warning. Since you haven't changed the level, the root logger's level is still warning. That means that it will ignore any logging with a level that is lower than warning, including debug loggings.
This is explained in the tutorial:
The 'info' line doesn't print anything, because the level is higher than info.
To change the level, just set it in the root logger:
In other words, it's not enough to define a handler with level=DEBUG, the actual logging level must also be DEBUG in order to get it to output anything.