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

2024-04-25 17:58:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将数据记录到stderr和一个文件中。所有log命令行应该只包含日志级别的消息。这在logging howto中描述了好几次,但它似乎对我不起作用。我创建了一个小测试脚本来说明我的问题:

#!/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.CRITICAL)我得到。。。在

^{pr2}$

现在有了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 CONSOLE和{}输出的来源,我期望的那些。我不知道INFO:me...或{}输出的来源,我想去掉它们。在

我已经试过了:

有人能帮我吗?这似乎是一个直截了当的要求,我真的不明白。在


Tags: testinfoissherrorhiloggerthis
1条回答
网友
1楼 · 发布于 2024-04-25 17:58:54

您可以将根级别设置为DEBUG,将propagate设置为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")

输出:

^{pr2}$

相关问题 更多 >

    热门问题