gpt4 book ai didi

Python 自定义记录器不打印到控制台

转载 作者:太空宇宙 更新时间:2023-11-04 02:14:37 25 4
gpt4 key购买 nike

我正在编写一个 Python Flask 应用程序,并且只想为我自己的代码设置日志级别。如果我将根记录器设置为 DEBUG,我会收到大量输出,所以我想我应该设置我自己的记录器,我可以为其设置日志级别。

这是在启动时运行的代码:

# File: server/__init__.py

import logging
def create_app(config=None):
log = logging.getLogger("api_log")
log.setLevel("DEBUG")
print("Log level: " + logging.getLevelName(log.level)) # Outputs "DEBUG"
log.debug("Does not show")
log.warning("Does show")

出于某种原因,即使将日志级别调整为 DEBUGlog.debug 命令也不会向文件输出任何内容。

任何人都可以发现我做错了什么吗?

编辑 #1:当我添加一个处理程序时,log.addHandler(logging.StreamHandler()) 在我的例子中,DEBUG 语句被输出到安慰。我不明白为什么我需要创建另一个处理程序来获得正确的输出。它还会打乱我的测试代码输出,但我会针对该问题创建另一篇文章。

最佳答案

以下两段来自Logging HOWTO文档解释了为什么必须设置处理程序:

Loggers have a concept of effective level. If a level is not explicitly set on a logger, the level of its parent is used instead as its effective level. If the parent has no explicit level set, its parent is examined, and so on - all ancestors are searched until an explicitly set level is found. The root logger always has an explicit level set (WARNING by default). When deciding whether to process an event, the effective level of the logger is used to determine whether the event is passed to the logger’s handlers.

Child loggers propagate messages up to the handlers associated with their ancestor loggers. Because of this, it is unnecessary to define and configure handlers for all the loggers an application uses. It is sufficient to configure handlers for a top-level logger and create child loggers as needed. (You can, however, turn off propagation by setting the propagate attribute of a logger to False.)

这里有两个关键点:

  1. 记录器将其消息传递给处理程序,以决定是否应记录该消息。
  2. 在您明确设置处理程序之前,使用了默认处理程序(其级别设置为警告)。

关于Python 自定义记录器不打印到控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52929580/

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