使用具有不同日志级别的多个处理程序时,会出现意外的python记录器输出

时间:2016-02-01 16:26:15

标签: python logging

我正在尝试将数据记录到stderr并进入文件。该文件应包含所有日志消息,并且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...输出的来源,我想摆脱它们。

我已经尝试过的事情:

有人可以帮助我吗?这似乎是一个简单的要求,我似乎真的没有得到它。

1 个答案:

答案 0 :(得分:3)

您可以将根级别设置为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