python - 为什么调用 logging.info 会改变我的记录器打印的内容?

标签 python logging

我正在尝试让 Python 记录内容,尽管已经阅读了 logging docshow-to ,我不明白它的行为。

我设置了全局日志级别,然后尝试记录一些东西:

logger = logging.getLogger()
print("Initially should be warn: %d" % logger.getEffectiveLevel())
logger.setLevel(logging.DEBUG)
print("Logger level: %d" % logger.getEffectiveLevel())

logger.info("Maybe I am printed?")

但是运行 python my_script.py 只是打印:

Initially should be warn: 30
Logger level: 10

但是,如果我添加一行 logging.info 调用,例如,

logger = logging.getLogger()
print("Initially should be warn: %d" % logger.getEffectiveLevel())
logger.setLevel(logging.DEBUG)
print("Logger level: %d" % logger.getEffectiveLevel())

logging.info("I am printed")
logger.info("Maybe I am printed?")

然后日志全部显示出来:

Initially should be warn: 30
Logger level: 10
INFO:root:I am printed
INFO:root:Maybe I am printed?

logging.info 在做什么?

最佳答案

第一个示例实际上会警告您找不到记录器“root”的处理程序(see here)。这是因为,如建议的那样,您没有为定义任何处理程序记录器

下面是logging.info的实现:

def info(msg, *args, **kwargs):
    """
    Log a message with severity 'INFO' on the root logger.
    """
    if len(root.handlers) == 0:
        basicConfig()
    root.info(msg, *args, **kwargs)

如您所见,当未找到处理程序时,它将调用 basicConfig,它还将负责初始化默认处理程序,从而修复您后续语句中的日志记录。

关于python - 为什么调用 logging.info 会改变我的记录器打印的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46568454/

相关文章:

python /元素树 : Write to file without namespaces

python - 如何生成具有不同图像的按钮

docker - 在容器优化操作系统中以 JSON 形式注入(inject)日志

windows - Windows 如何记录硬件错误?

python - Django 和 fcgi - 日志记录问题

c++ - 如何在 C++ 中读取不断增长的文本文件?

python - 使用 BeautifulSoup4 和 Python 3 解析 html 表

python - 类型错误 : descriptor 'strftime' requires a 'datetime.date' object but received a 'Text'

python - 将 dict 字符串转换为字典列表以插入到 mongodb

java - 记录完整堆栈跟踪性能问题