在我正在编写的python脚本中,我试图使用日志模块记录事件。我有以下代码来配置我的记录器:
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)
当我尝试运行logging.debug(“一些字符串”)时,我没有得到控制台的输出,尽管文档中的这一页说logging.debug应该让根记录器输出消息。为什么我的程序不输出任何东西,我该如何修复它?
这个问题浪费了我很多时间,所以我要花更多的时间来写一个答案来节省你的时间
问题
无法为自定义记录器设置日志级别。(例如:调试级)
什么不起作用
将日志级别设置为处理程序。
import logging
# Get logger
logger = logging.getLogger("my logger")
# Create a handler and set logging level for the handler
c_handler = logging.StreamHandler()
c_handler.setLevel(logging.DEBUG) # <- Here things went wrong
# link handler to logger
logger.addHandler(c_handler)
# test
logger.debug('This is a debug message') # WILL NOT WORK
解决方案
通过记录器对象(而不是处理程序)设置日志级别
import logging
# Get logger
logger = logging.getLogger("my logger")
# Create a handler
c_handler = logging.StreamHandler()
# link handler to logger
logger.addHandler(c_handler)
# Set logging level to the logger
logger.setLevel(logging.DEBUG) # <-- THIS!
# test
logger.debug('This is a debug message') # WILL WORK
默认日志级别为warning。
因为您没有更改级别,所以根日志记录器的级别仍然是警告。
这意味着它将忽略级别低于警告的任何日志记录,包括调试日志记录。
这在教程中有解释:
import logging
logging.warning('Watch out!') # will print a message to the console
logging.info('I told you so') # will not print anything
'info'行不打印任何东西,因为级别比info高。
要更改级别,只需在根日志记录器中设置它:
'root':{'handlers':('console', 'file'), 'level':'DEBUG'}
换句话说,用level=DEBUG定义处理程序是不够的,实际的日志级别也必须是DEBUG,以便让它输出任何东西。
对于这里想要一个超级简单的答案的任何人:设置你想要显示的级别。在我所有脚本的顶部,我只是放:
import logging
logging.basicConfig(level = logging.INFO)
然后显示在该级别或以上的任何内容:
logging.info("Hi you just set your fleeb to level plumbus")
它是一个有五个级别的分层集,因此日志将显示在您设置的级别或更高的级别。因此,如果想要显示错误,可以使用日志记录。错误(“plumbus is broken”)。
级别由高到低依次为:DEBUG、INFO、WARNING、ERROR和CRITICAL。默认设置为WARNING。
这是一篇很好的文章,包含了比我的回答更好的信息:
https://www.digitalocean.com/community/tutorials/how-to-use-logging-in-python-3