未应用日志记录级别

时间:2020-07-26 13:27:22

标签: python python-3.x logging

似乎在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

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

1 个答案:

答案 0 :(得分:1)

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

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

调用logging.debug时,会为您调用logging.basicConfig,因为根记录器没有处理程序。此时,创建了一个StreamHandler,但是根记录器仍处于默认级别INFO,因此没有任何内容发送到新处理程序。

现在,当您再次调用test_logger.debug时,它具有继承的StreamHandler,可以将长消息实际输出为标准错误。