如何引发python异常并包含Sentry的附加数据?

2024-03-28 11:13:39 发布

您现在位置:Python中文网/ 问答频道 /正文

哨兵可以检测与异常相关的附加数据,例如:

enter image description here

如何从Python(它是一个Django应用程序)中使用自己的additional data字段引发这样的异常?。


Tags: 数据django应用程序dataadditional哨兵
3条回答

您可以尝试以下两种方法之一:

>>> # Raise the exception with the data you want.
>>> raise Exception('extra information')
Traceback (most recent call last):
  File "<pyshell#64>", line 1, in <module>
    raise Exception('extra information')
Exception: extra information
>>> # Catch an exception and add extra arguments.
>>> try:
    raise Exception()
except Exception as error:
    error.args += ('extra information',)
    raise

Traceback (most recent call last):
  File "<pyshell#68>", line 2, in <module>
    raise Exception()
Exception: extra information
>>> 

通过添加更多参数,可以添加任意多个附加数据字段。

wes' answer没有帮到我,因为我实际上想引发一个异常,不仅记录它。

以下是我所做的(client是Raven Sentry的客户):

client.extra_context({'foo': 'bar'})
raise RuntimeError('Whoops, something went wrong!')

我使用logging库记录异常,因此在稍微调试代码之后,我注意到extra参数:

import logging
logger = logging.getLogger('my_app_name')

def do_something():

    try:
        #do some stuff here that might break

    except Exception, e:
        logger.error(e, exc_info=1, extra={'extra-data': 'blah', })

传递exc_info=1与调用logger.exception相同。但是,exception()不接受kwargs,这是使用extra参数所必需的。

这些值将显示在Sentry错误仪表板的“附加数据”部分。

相关问题 更多 >