gpt4 book ai didi

python - 简单的调试级 Python 日志记录失败?

转载 作者:行者123 更新时间:2023-11-28 22:50:31 24 4
gpt4 key购买 nike

这是我在 Python 3.3.2 下运行的一些代码:

import logging

logger = logging.getLogger("test.logger")

logging.getLogger().setLevel(logging.DEBUG) # Shouldn't be needed
logger.setLevel(logging.DEBUG)

print("Effective logging level is {}".format(logger.getEffectiveLevel()))
logger.debug("This is a debug-level message.")

这是输出:

Effective logging level is 10

所以尽管记录器的级别看起来是正确的,但调试消息并没有被写入。我在 Python 文档或本网站上没有看到任何表明我遗漏了任何内容的内容。这里发生了什么?谢谢。

编辑:如果我通过添加此行来使用根记录器...

logging.debug("Try this")

...然后两条消息都出来了。 (注意使用 logging 而不是 logger。)越来越好奇。

最佳答案

Amber 的回答是正确的。我可以告诉您为什么您看到的是 WARNING 或更高级别的消息,而不是 INFODEBUG

来自documentation对于 3.2:

logging.lastResort - A “handler of last resort” is available through this attribute. This is a StreamHandler writing to sys.stderr with a level of WARNING, and is used to handle logging events in the absence of any logging configuration. The end result is to just print the message to sys.stderr. This replaces the earlier error message saying that “no handlers could be found for logger XYZ”. If you need the earlier behaviour for some reason, lastResort can be set to None.

请注意上面的粗体部分 - 这就是为什么您没有看到 WARNING 下方消息的原因。只需添加一行

logger.addHandler(logging.StreamHandler())

logger.debug(...) 行之前,您会看到 DEBUG 消息出现。

当您调用 logging.debug(...) 时,如果没有处理程序,这会将 StreamHandler 添加到根记录器(如注释中所述)在 here 下方),这就是出现这两条消息的原因。

关于python - 简单的调试级 Python 日志记录失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22550421/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com