我有一个在cron定期运行的服务器上的python刮板。 有时它会崩溃,但我不知道是什么让它崩溃,崩溃的原因是因为没有任何与日志中的exception相关:既不提及错误,也不提供堆栈跟踪。 logging器是这样设置的:
logging.basicConfig(filename="log.log", level=logging.INFO)
但是在例外情况下,无论如何都必须login到日志中,是不是这样?
问题是,我怎样才能findexception的来源。
记录崩溃信息的标准Python模块称为traceback
。 实际上,您需要在最高级别安装一个catch-all异常处理程序,并调用logging.error(traceback.format_exc())
。
"""The main module of the application that is called from the command line or cron""" import logging import traceback # import other modules used by this one import some_stuff class A: # whatever def foo(): # whatever if __name__ == "__main__": logging.basicConfig(filename="/path/log.log", level=logging.INFO) try: # The top-level logic of the program goes here var = A() foo() # whatever except: # This a catch-all exception handler for any stuff that was not # not properly handled by the program logic. logging.error(traceback.format_exc())
请注意,如果您正在使用在C / C ++中实现的Python扩展模块,并且在这样的模块内发生崩溃(例如,分段错误),程序仍然会以静默方式崩溃。 没有简单的解决方法。
你可以使用这样的东西来检查你正在得到什么异常。
try: #the code which may throw exception except Exception as e: #log the exception over here.