sys.excepthook在导入的模块中不起作用

Eli*_*ria 6 python logging exception

我正在尝试设计一个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
Run Code Online (Sandbox Code Playgroud)

如果我从命令行(./loggingTest.py)运行此程序,则效果很好。异常被记录,我看到以下输出:

outside of exception handler: logger = <logging.RootLogger object at 0x7f2022eab950>
inside exception handler: logger = <logging.RootLogger object at 0x7f2022eab950>
Run Code Online (Sandbox Code Playgroud)

但是,如果我运行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
Run Code Online (Sandbox Code Playgroud)

我也许可以通过再次在sys.excepthook中导入日志记录模块来解决此问题,但我仍然很好奇:为什么会这样?

Eli*_*ria 4

我将此问题报告为Python 错误跟踪器上的错误。到目前为止,有人回应称Python 2.7和2.7.1之间肯定存在变化,他认为这是预期的行为。他建议像这样记录所有异常:

def handleException(excType, excValue, traceback, logger=logger):
    logger.error("Uncaught exception", exc_info=(excType, excValue, traceback))

sys.excepthook = handleException
Run Code Online (Sandbox Code Playgroud)