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



我正在尝试将数据记录到 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...输出来自哪里,我想摆脱它们。

我已经尝试过的事情:

  • 创建筛选器,如下所述:https://stackoverflow.com/a/7447596/902327(不起作用(
  • 使用logger.handlers = []从记录器中清空处理程序(也不起作用(

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

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

相关内容

最新更新