我想捕獲所有的異常並使用下面的代碼將它們記錄到日誌文件中,但由於某種原因,它不會捕獲它們。該代碼是: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
而且,如上所述,日誌文件沒有捕獲任何東西。我做錯了什麼?
謝謝!
我不確定iPython依賴於這個鉤子。我認爲它自己有一個鉤子。如果未來24小時內沒有提供,我會盡力寫出更好的答案。 – Josay
請參閱http://stackoverflow.com/questions/1261668/cannot-override-sys-excepthook(可能重複的問題...) – Josay
喬塞,感謝您的意見。儘管標記爲重複的答案有幾個共同點,但是在這個問題中選擇的答案並不是正確的答案,這可能是你的答案。將嘗試你的方法,並回到你身邊。 – Escachator