Python日志记录不输出任何东西

在我正在编写的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("Some string")时,我没有得到控制台的输出,尽管文档中的这一页logging.debug应该让根记录器输出消息。为什么我的程序不输出任何东西,我该如何修复它?

234347 次浏览

默认日志级别为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,以便让它输出任何东西。

试试这个?似乎在删除我的案例中的所有处理程序后,问题就解决了。

for handler in logging.root.handlers[:]:
logging.root.removeHandler(handler)


logging.basicConfig(filename='output.log', level=logging.INFO)

许多年后,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

根据您的运行时环境和日志级别,第一行日志(在基本配置之前)可能不会出现在任何地方. exe将被删除。

对于这里想要一个超级简单的答案的任何人:设置你想要显示的级别。在我所有脚本的顶部,我只是放:

import logging
logging.basicConfig(level = logging.INFO)

然后显示在该级别或以上的任何内容:

logging.info("Hi you just set your fleeb to level plumbus")

它是一个有五个级别的分层集,所以日志将显示在你设置的级别,或更高的。所以如果你想显示一个错误,你可以使用logging.error("The plumbus is broken")

这些级别按照严重程度的递增顺序为DEBUGINFOWARNINGERRORCRITICAL。默认设置为WARNING

这是一篇很好的文章,包含了比我的答案更好的信息:
https://www.digitalocean.com/community/tutorials/how-to-use-logging-in-python-3 < / p >
< p > import logging < br > log = logging.getLogger() < br > log.setLevel(logging.DEBUG) < br > < / p >

这段代码将默认日志级别设置为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

解决方案

通过记录器对象(而不是处理程序)Customlogger.setLevel(logging.DEBUG)设置日志级别

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

调用removeHandler()函数会留下stdout/stderr输出,即使所有处理程序都已删除。

清除日志记录器的一种方法是清空处理程序列表,例如: 记录器。Handlers = [] 或 Logger.root.handlers = []

这对我很管用。