【发布时间】:2017-09-15 21:00:16
【问题描述】:
我正在尝试捕获所有异常并使用以下代码将它们记录到日志文件中,但由于某种原因它没有捕获它们。代码是:
# 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 小时内没有提供任何答案,我会尝试写一个更好的答案。
-
见stackoverflow.com/questions/1261668/…(可能重复的问题...)
-
Josay,感谢您的 cmets。尽管标记为重复的答案有一些共同点,但该问题中选择的答案不是正确答案,可能是您的答案。将尝试您的方法并回复您。
标签: python logging error-handling exception-handling sys