我正在编写一个终端应用程序,在传入-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, inlog.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
Sebastian.. 17
代替
handler = logging.StreamHandler(stdout).setFormatter(formatter)
尝试:
handler = logging.StreamHandler(stdout) handler.setFormatter(formatter)
发生的事情是,在第一种情况下,您setFormatter()
要为handler
变量分配返回值,但setFormatter()
不返回处理程序(即返回None
)
代替
handler = logging.StreamHandler(stdout).setFormatter(formatter)
尝试:
handler = logging.StreamHandler(stdout) handler.setFormatter(formatter)
发生的事情是,在第一种情况下,您setFormatter()
要为handler
变量分配返回值,但setFormatter()
不返回处理程序(即返回None
)