【发布时间】:2019-11-17 19:56:21
【问题描述】:
在 Python 中记录异常的最正确方法是什么?
有些人只记录e,另一个日志属性e.message(但在某些例外情况下可能会丢失)。
一种使用str() 来捕获异常的描述,但它不包含错误类型,有时没有它是无用的。
实际上repr() 将返回错误类型和描述,但它并不那么受欢迎(在我看到的项目中)。
另一个相关问题:这如何影响收集和分组错误/警报(如 Sentry)的服务。它们还应该包含一些关于具体错误的信息。
所以想再次开启这个讨论:哪种记录异常的方式最好用?
def foo():
""" Method that can raise various types of exceptions """
1/0 # just for example
try:
foo()
except Exception as e:
logger.exception('Error occurred during execution: %s', e) # 1
logger.exception('Error occurred during execution: %s', e.message) # 2
logger.exception('Error occurred during execution: %s', str(e)) # 3
logger.exception('Error occurred during execution: %s', str(e.message)) # 4
logger.exception('Error occurred during execution: %s', repr(e)) # 5
找到了一个旧讨论 here,但它没有使用 logging 库,并且可能从那一刻起发生了一些变化。
附:我知道如何获得追溯和任何其他相关信息。这里的问题应该是记录异常和错误的一般规则。
【问题讨论】:
-
你的意思是甚至不需要在消息中添加
e作为参数吗?也许我需要用logger.error(...)的使用案例来更新这个问题 -
@olinox14 以及这将如何影响通过这些日志收集和分组问题的服务(例如 Sentry)。
-
是的,不需要添加
e,但是你可以这样做,异常的消息将被记录,然后是错误的回溯。而且我不知道Sentry,我从来没有用过它......
标签: python python-logging