我正在尝试设计一个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)运行此程序,它将正常工作.异常被记录,我