【发布时间】: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 CONSOLE 和ERROR FILE 输出的来源,这是我所期望的。我不知道INFO:me... 或ERROR:me... 输出的来源,我想摆脱它们。
我已经尝试过的事情:
- 按照此处所述创建过滤器:https://stackoverflow.com/a/7447596/902327(不起作用)
- 使用
logger.handlers = []从记录器中清空处理程序(也不起作用)
有人可以帮我吗?这似乎是一个简单的要求,我似乎真的不明白。
【问题讨论】: