Python 具有格式化程序的日志记录模块导致 AttributeError

Python logging module having a formatter causes AttributeError

我正在编写一个终端应用程序,在传入 -v 选项后,毫不奇怪,它变得冗长。我想在终端中提供输出,以便于测试(无论如何,当 运行 作为 cron 时,它会被重定向到一个日志文件)。

但是,python logging 模块不允许我在使用格式化程序时写出相应级别的消息。 (格式化程序直接从Python Logging Cookbok复制过来)

此行为不仅限于 Python3。 Python2.7 在给定条件下引发相同的异常。


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() 的 return 分配给 handler 变量,但 setFormatter() 没有 return 处理程序(即它 returns None