Jupyter Python中的异常捕获器不起作用(sys.excepthook)



我正在尝试捕获所有异常,并将它们记录到日志文件中,但由于某种原因,它不会捕获它们。代码是:

# Prepares logging
import logging
import time
output_folder='whatever'
# Logging to file:
today=time.strftime("%Y%M%d %H:%M:%S")
logging.basicConfig(filename=output_folder+'/logger '+today+'.log',level=logging.DEBUG,
                    format='%(asctime)s %(message)s', filemode='w')
logging.info('Program started.')
# Every time there is an error, catch it
import sys
#def error_catching(exctype, value, tb):
def log_uncaught_exceptions(ex_cls, ex, tb):
    print "Error found"
    logging.critical(''.join(traceback.format_tb(tb)))
    logging.critical('{0}: {1}'.format(ex_cls, ex))
sys.excepthook = log_uncaught_exceptions

然后我生成一个错误,例如,调用一个不存在的变量('M'(,我会收到错误,但没有登录记录文件中的登录:

m #this should generate a NameError, which is the following
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-9-69b64623f86d> in <module>()
----> 1 m
NameError: name 'm' is not defined

,如所说,日志文件没有捕获任何内容。我做错了什么?

谢谢!

免责声明:显然,一个带有开放赏金的问题不能关闭。因此,我的答案主要基于其他类似的问题/答案

更改sys.excepthook在ipython上不起作用。

解决方法是更新IPython.core.interactiveshell.InteractiveShell.showtraceback

您将在某些项目(例如Danrobinson/traceStack。

最新更新