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

时间:2015-12-16 18:30:59

标签: python logging stdout standard-library 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

1 个答案:

答案 0 :(得分:15)

而不是

handler = logging.StreamHandler(stdout).setFormatter(formatter)

尝试:

handler = logging.StreamHandler(stdout)
handler.setFormatter(formatter)

正在发生的事情是,在第一种情况下,您将setFormatter()的返回值分配给handler变量,但setFormatter()不返回处理程序(即返回{{1} }})