我可能在这里错误地表达了这个问题,但我刚刚观察到了python的日志记录模块的奇怪行为。以下代码段不起作用,至少在OSX
上import logging
import sys
root = logging.getLogger()
root.addHandler(
logging.StreamHandler(stream=sys.stdout).setFormatter(
logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
))
root.setLevel(logging.INFO)
root.info('initializing ...')
以上代码产生此异常
root.info('initializing ...') File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 1165, in info self._log(INFO, msg, args, **kwargs) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 1284, in _log self.handle(record) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 1294, in handle self.callHandlers(record) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 1333, in callHandlers if record.levelno >= hdlr.level: AttributeError: 'NoneType' object has no attribute 'level'
另一方面,类似的代码片段完全正常。
import logging
import sys
root = logging.getLogger()
handler = logging.StreamHandler(stream=sys.stdout)
formatter = logging.Formatter(
fmt='%(asctime)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
root.addHandler(handler)
root.setLevel(logging.INFO)
root.info('initializing...')
第二个代码段的作用是什么?