在我正在编写的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应该让根记录器输出消息。为什么我的程序不输出任何东西,我该如何修复它?
许多年后,Python日志记录器似乎仍然存在可用性问题。下面是一些解释和例子:
import logging
# This sets the root logger to write to stdout (your console).
# Your script/app needs to call this somewhere at least once.
logging.basicConfig()
# By default the root logger is set to WARNING and all loggers you define
# inherit that value. Here we set the root logger to NOTSET. This logging
# level is automatically inherited by all existing and new sub-loggers
# that do not set a less verbose level.
logging.root.setLevel(logging.NOTSET)
# The following line sets the root logger level as well.
# It's equivalent to both previous statements combined:
logging.basicConfig(level=logging.NOTSET)
# You can either share the `logger` object between all your files or the
# name handle (here `my-app`) and call `logging.getLogger` with it.
# The result is the same.
handle = "my-app"
logger1 = logging.getLogger(handle)
logger2 = logging.getLogger(handle)
# logger1 and logger2 point to the same object:
# (logger1 is logger2) == True
logger = logging.getLogger("my-app")
# Convenient methods in order of verbosity from highest to lowest
logger.debug("this will get printed")
logger.info("this will get printed")
logger.warning("this will get printed")
logger.error("this will get printed")
logger.critical("this will get printed")
# In large applications where you would like more control over the logging,
# create sub-loggers from your main application logger.
component_logger = logger.getChild("component-a")
component_logger.info("this will get printed with the prefix `my-app.component-a`")
# If you wish to control the logging levels, you can set the level anywhere
# in the hierarchy:
#
# - root
# - my-app
# - component-a
#
# Example for development:
logger.setLevel(logging.DEBUG)
# If that prints too much, enable debug printing only for your component:
component_logger.setLevel(logging.DEBUG)
# For production you rather want:
logger.setLevel(logging.WARNING)
一个常见的混淆来源是一个初始化不好的根日志记录器。考虑一下:
import logging
log = logging.getLogger("myapp")
log.warning("woot")
logging.basicConfig()
log.warning("woot")
输出:
woot
WARNING:myapp:woot
根据您的运行时环境和日志级别,第一行日志(在基本配置之前)可能不会出现在任何地方。
对于这里想要一个超级简单的答案的任何人:设置你想要显示的级别。在我所有脚本的顶部,我只是放:
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
这个问题浪费了我很多时间,所以我要花更多的时间来写一个答案来节省你的时间
问题
无法为自定义记录器设置日志级别。(例如:调试级)
什么不起作用
将日志级别设置为处理程序。
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