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

Exception catcher in Jupyter Python not working (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

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

谢谢!

免责声明:显然,有悬赏的问题无法关闭。因此,我的回答主要基于 this other similar question/answer.

更改 sys.excepthook 不适用于 iPython。

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

您会在某些项目(例如 danrobinson/tracestack.

中找到额外的解释和修复的实现。