具有格式化程序的Python日志记录模块导致AttributeError [英] Python logging module having a formatter causes AttributeError

查看:298
本文介绍了具有格式化程序的Python日志记录模块导致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 (工作原理很简单)


two.py (works like a charm)

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆