首页 > 解决方案 > 未应用日志记录级别

问题描述

似乎在 python 中设置记录器(包括根记录器)的日志记录级别没有应用,直到您使用日志记录模块的日志记录功能之一。这是一些代码来说明我的意思(我使用了 python 3.7):

import logging


if __name__ == "__main__":
    # Create a test logger and set its logging level to DEBUG
    test_logger = logging.getLogger("test")
    test_logger.setLevel(logging.DEBUG)

    # Log some debug messages
    # THESE ARE NOT PRINTED
    test_logger.debug("test debug 1")

    # Now use the logging module directly to log something
    logging.debug("whatever, you won't see this anyway")

    # Apparently the line above "fixed" the logging for the custom logger
    # and you should be able to see the message below
    test_logger.debug("test debug 2")

输出:

DEBUG:test:test debug 2

也许我对记录器的配置有误解,在这种情况下,我很高兴知道正确的做法。

标签: pythonpython-3.xlogging

解决方案


您没有(明确)调用logging.basicConfig,因此处理程序配置不正确。

test_logger最初没有处理程序,因为您没有添加一个并且根记录器还没有一个。因此,尽管该消息是“记录的”,但没有任何定义它的实际含义。

当您调用时logging.debuglogging.basicConfig会为您调用,因为根记录器没有处理程序。此时,StreamHandler创建了 a ,但根记录器保持在默认级别INFO,因此不会向新处理程序发送任何内容。

现在当你test_logger.debug再次调用时,它继承StreamHandler了实际将长消息输出到标准错误。


推荐阅读