【问题标题】:Python exception logging, correct syntax?Python异常记录,正确的语法?
【发布时间】:2012-02-14 14:44:22
【问题描述】:

我正在向一些处理异常的 python 代码添加日志记录,在下面的示例中,当发生 TypeError 或 AttributeError 时,想要记录异常详细信息(例如通过 logger.exception())的正确语法是什么?

    try:
        ...
    except (TypeError, AttributeError):
        # want to do a logger.exception(x) here but not sure what to use for x
        ...
        raise CustomError("Unable to parse column status)

【问题讨论】:

    标签: python logging exception-handling


    【解决方案1】:

    exception(...) 只是一种方便的方法,它像其他方法一样接收消息:

    def exception(self, msg, *args):
        """
        Convenience method for logging an ERROR with exception information.
        """
        self.error(msg, exc_info=1, *args)
    

    所以你可以像这样使用它

    logger.exception("Some error message")
    

    并且日志处理程序将自动从当前异常中添加异常信息。仅在异常处理程序中使用它(即在 except: 块中)!

    【讨论】:

    • 好的,我试试,我不知道信息。将记录当前异常(如果可能捕获多个)。
    【解决方案2】:

    如果你想要异常细节,你需要将异常本身绑定到一个局部变量,像这样:

    except (TypeError, AttributeError), e:
        # e is the Exception object
        logger.exception(e)
    

    如果你需要根据异常的类型做不同的事情,那么你可以分别捕获它们:

    except TypeError, e:
        logger.exception('There was a Type Error; details are %s' % e)
        # Do something, or raise another exception
    except AttributeError, e:
        logger.exception('There was an Attribute Error; details are %s' % e)
        # Do something, or raise another exception
    

    如果您需要有关异常本身上下文的更多信息,请查看sys.exc_info() 函数;它可以为您提供回溯,以及有关异常发生的确切位置的详细信息。

    【讨论】:

    • exception(...),或更准确地说,exc_info=True 参数包含来自sys.exc_info() 的异常信息,以便记录器实现可以使用它。那么为什么要手动格式化呢?
    • 这更多地用于一般的异常处理逻辑,以防可以用信息做一些有用的事情。不,如果您要做的只是将其格式化为日志消息,则没有理由将其从 exc_info 中提取出来。
    • 我的意思是 'message %s' % e 应该logging.exception 调用一起使用,因为异常信息会自动存储并由配置的记录器实现使用以记录堆栈跟踪,例如。无需自己格式化。
    猜你喜欢
    • 1970-01-01
    • 2019-11-17
    • 1970-01-01
    • 2017-04-13
    • 1970-01-01
    • 2015-09-17
    • 1970-01-01
    • 2013-01-29
    • 1970-01-01
    相关资源
    最近更新 更多