【发布时间】:2011-07-24 00:45:12
【问题描述】:
我正在尝试设计一个 Python 程序,该程序使用日志记录模块记录所有未捕获的异常。我通过使用 sys.excepthook 函数来覆盖默认的异常处理来做到这一点。我注意到如果我直接从命令行运行程序,它工作正常,但如果我尝试导入文件,它就不起作用。似乎 sys.excepthook 函数不知道日志记录模块。这是一个例子:
#! /usr/bin/env python2.7
import logging, sys
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.FileHandler("test.log"))
print "outside of exception handler: logger = %s" % logger
def handleException(excType, excValue, traceback):
#global logger # this function doesn't work whether or not I include this line
print "inside exception handler: logger = %s" % logger
logger.error("Uncaught exception", exc_info=(excType, excValue, traceback))
sys.excepthook = handleException
logger.debug("starting")
asdf # create an exception
如果我从命令行 (./loggingTest.py) 运行它,它工作正常。异常被记录,我看到了这个输出:
outside of exception handler: logger = <logging.RootLogger object at 0x7f2022eab950>
inside exception handler: logger = <logging.RootLogger object at 0x7f2022eab950>
但是,如果我运行 Python 解释器并尝试导入文件 (import loggingTest),它的行为会很奇怪。没有记录异常,我看到了这个:
outside of exception handler: logger = <logging.RootLogger object at 0x7f8ab04f3ad0>
inside exception handler: logger = None
Error in sys.excepthook:
Traceback (most recent call last):
File "loggingTest.py", line 13, in handleException
logger.error("Uncaught exception", exc_info=(excType, excValue, traceback))
AttributeError: 'NoneType' object has no attribute 'error'
Original exception was:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "loggingTest.py", line 18, in <module>
asdf # create an exception
NameError: name 'asdf' is not defined
我也许可以通过在 sys.excepthook 中再次导入日志记录模块来解决这个问题,但我仍然很好奇:为什么会发生这种情况?
【问题讨论】: