【问题标题】:Unexpected python logger output when using several handlers with different log levels使用具有不同日志级别的多个处理程序时出现意外的 python 记录器输出
【发布时间】:2016-02-02 01:12:08
【问题描述】:

我正在尝试将数据记录到标准错误和文件中。该文件应该包含 所有 日志消息,并且到 stderr 应该只进入命令行上配置的日志级别。这在日志记录方法中多次描述 - 但它似乎对我不起作用。我创建了一个小测试脚本来说明我的问题:

#!/usr/bin/env python

import logging as l

l.basicConfig(level=100)
logger = l.getLogger("me")

# ... --- === SEE THIS LINE === --- ...
logger.setLevel(l.CRITICAL)

sh = l.StreamHandler()
sh.setLevel(l.ERROR)
sh.setFormatter(l.Formatter('%(levelname)-8s CONSOLE %(message)s'))
logger.addHandler(sh)

fh = l.FileHandler("test.dat", "w")
fh.setLevel(l.DEBUG)
fh.setFormatter(l.Formatter('%(levelname)-8s    FILE %(message)s'))
logger.addHandler(fh)

logger.info("hi this is INFO")
logger.error("well this is ERROR")

在第 5 行代码行中,我可以选择 logger.setLevel(l.CRITICAL)logger.setLevel(l.DEBUG)。这两个结果都不令人满意。

使用 logger.setLevel(l.CRITICAL) 我得到...

$ python test.py
$ cat test.dat  
$

现在有了logger.setLevel(l.DEBUG),我明白了……

$ python test.py
INFO:me:hi this is INFO
ERROR    CONSOLE well this is ERROR
ERROR:me:well this is ERROR
$ cat test.dat  
INFO        FILE hi this is INFO
ERROR       FILE well this is ERROR
$

在一种情况下,我什么都看不到,在另一种情况下,我到处都能看到,并且一条消息甚至在控制台上显示了两次。

现在我得到了ERROR CONSOLEERROR FILE 输出的来源,这是我所期望的。我知道INFO:me...ERROR:me... 输出的来源,我想摆脱它们。

我已经尝试过的事情:

有人可以帮我吗?这似乎是一个简单的要求,我似乎真的不明白。

【问题讨论】:

    标签: python logging


    【解决方案1】:

    您可以将根级别设置为 DEBUG,将传播设置为 False,然后为其他处理程序设置适当的级别。

    import logging as l
    
    l.basicConfig()
    logger = l.getLogger("me")
    
    # ... --- === SEE THIS LINE === --- ...
    logger.setLevel(l.DEBUG)
    logger.propagate = False
    sh = l.StreamHandler()
    sh.setLevel(l.ERROR)
    
    sh.setFormatter(l.Formatter('%(levelname)-8s CONSOLE %(message)s'))
    logger.addHandler(sh)
    
    fh = l.FileHandler("test.dat", "w")
    fh.setLevel(l.INFO)
    fh.setFormatter(l.Formatter('%(levelname)-8s    FILE %(message)s'))
    logger.addHandler(fh)
    
    logger.info("hi this is INFO")
    
    logger.error("well this is ERROR")
    

    输出:

    ~$ python test.py
    ERROR    CONSOLE well this is ERROR
    ~$ cat test.dat
    INFO        FILE hi this is INFO
    ERROR       FILE well this is ERROR
    

    【讨论】:

    • 不用担心,当您将级别设置为关键时,这意味着只有关键级别的消息才会发送到其他处理程序。
    猜你喜欢
    • 2014-09-30
    • 1970-01-01
    • 2015-03-21
    • 2014-12-25
    • 1970-01-01
    • 2020-03-27
    • 2016-04-15
    • 1970-01-01
    • 2011-11-02
    相关资源
    最近更新 更多