【问题标题】:Unable to find the source of an exception and what an exception it is无法找到异常的来源以及它是什么异常
【发布时间】:2017-05-10 15:21:30
【问题描述】:

我有一个由 cron 定期运行的服务器上的 python 刮板。有时它会崩溃,但我无法弄清楚是什么导致它崩溃以及它在哪里崩溃,因为日志中没有任何与异常相关的内容:既没有提及错误,也没有堆栈跟踪。记录器是这样设置的:

logging.basicConfig(filename="log.log", level=logging.INFO)

但是万一出现异常,无论如何都要记入日志,不是吗?

问题是,我怎样才能找到异常的来源。

【问题讨论】:

  • 将日志级别更改为 logging.DEBUG。这将在日志文件中打印更多信息。这将帮助您更好地调试。

标签: python linux python-3.x exception logging


【解决方案1】:

您可以使用类似的方法来检查您遇到了什么异常。

try:
   #the code which may throw exception
except Exception as e:
   #log the exception over here.

【讨论】:

    【解决方案2】:

    记录崩溃信息的标准 Python 模块称为traceback。本质上,您需要在最顶层安装一个包罗万象的异常处理程序,并调用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 扩展模块,并且此类模块内部存在崩溃(例如,分段错误),则程序仍会静默崩溃。解决这个问题并不容易。

    【讨论】:

    • logging.error(traceback.format_exc()) -- 我无法调用它,因为我不知道异常的来源
    • 你不需要知道来源。我将在我的答案中添加一个示例。
    • 你不懂。我有一个大程序。如果我不知道它在哪里崩溃,我应该在哪里插入“try except”?
    • 您应该将它插入到主模块中,该模块是从cron 作业中调用的。您将模块的主循环与 try: ... except: 夹在中间。
    • 扩展示例
    猜你喜欢
    • 2013-08-22
    • 2012-02-11
    • 2011-08-16
    • 2017-12-25
    • 2012-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-26
    相关资源
    最近更新 更多