具有格式化程序的 Python 日志记录模块会导致 AttributeError [英] Python logging module having a formatter causes AttributeError
问题描述
我正在编写一个终端应用程序,它在传入 -v
选项后,不出所料地变得冗长.我想在终端中提供输出,以便于测试(无论如何,当作为 cron 运行时,它会被重定向到日志文件).
I am writing a terminal application, which, after passing in -v
option, gets, unsurprisingly, verbose. I want to have the output available in the terminal, for easy testing (it gets redirected to a log file when running as cron anyways).
但是,python logging
模块不允许我在使用格式化程序时写出具有相应级别的消息.(格式化程序直接从Python Logging Cookbok复制而来)
However, python logging
module doesn't allow me to write out the messages with corresponding levels when using a formatter. (Formatter is copied directly from Python Logging Cookbok)
此行为不仅限于 Python3.Python2.7 在给定条件下引发相同的异常.
This behavior is not limited to Python3 only. Python2.7 raises the same exception under the given conditions.
one.py
from sys import stdout
import logging
if __name__ == '__main__':
level = 20
log = logging.getLogger()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler = logging.StreamHandler(stdout).setFormatter(formatter)
log.addHandler(handler)
log.setLevel(level)
log.info("Blah")
one.py 输出
Traceback (most recent call last):
File "/home/tlevi/PycharmProjects/untitled/main.py", line 14, in <module>
log.info("Blah")
File "/usr/lib/python3.4/logging/__init__.py", line 1279, in info
self._log(INFO, msg, args, **kwargs)
File "/usr/lib/python3.4/logging/__init__.py", line 1414, in _log
self.handle(record)
File "/usr/lib/python3.4/logging/__init__.py", line 1424, in handle
self.callHandlers(record)
File "/usr/lib/python3.4/logging/__init__.py", line 1485, in callHandlers
if record.levelno >= hdlr.level:
AttributeError: 'NoneType' object has no attribute 'level'
<小时>
two.py(效果很好)
from sys import stdout
import logging
if __name__ == '__main__':
level = 20
log = logging.getLogger()
handler = logging.StreamHandler(stdout)
log.addHandler(handler)
log.setLevel(level)
log.info("Blah")
two.py 输出
Blah
推荐答案
代替
handler = logging.StreamHandler(stdout).setFormatter(formatter)
试试:
handler = logging.StreamHandler(stdout)
handler.setFormatter(formatter)
发生的情况是,在第一种情况下,您将 setFormatter()
的返回值分配给 handler
变量,但是 setFormatter()
> 不返回处理程序(即它返回 None
)
What is happening is that in the first case you are assigning the return of setFormatter()
to the handler
variable, but setFormatter()
does not return the handler (i.e. it returns None
)
这篇关于具有格式化程序的 Python 日志记录模块会导致 AttributeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!