相关疑难解决方法(0)

具有格式化程序的Python日志记录模块会导致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")
Run Code Online (Sandbox Code Playgroud)

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) …
Run Code Online (Sandbox Code Playgroud)

python logging stdout standard-library attributeerror

6
推荐指数
1
解决办法
1万
查看次数