02Sentry——捕获消息

2020-08-13  本文已影响0人  转身丶即天涯

虽然sentry可以自动捕捉异常消息,但是开发过程中经常会打印一些信息,如果我们在sentry的页面上也想看到消息时,就需要用到捕获消息。

我们来探索一下,都有哪些捕获方式。


1. 自动捕获

这就不说了,只要在项目中执行sentry_sdk.init()方法后,就会自动捕获。

2. 利用capture_exception()在外层捕获

import sentry.sentry_log
from sentry_sdk import capture_exception

from src import logic_code


if __name__ == "__main__":
    try:
        logic_code.devision(10 / 0)
    except Exception as e:
        capture_exception(e)
image.png

结果并不理想,我们只是捕获到外层调用的函数,并未找到报错的具体位置。

image.png
是的,错误应该是在 return a / b 这里触发的。所以带着问题继续探索吧。

3. 使用logging.error()主动报错

import logging

import sentry.sentry_log
from sentry_sdk import capture_exception

from src import logic_code


if __name__ == "__main__":
    try:
        logic_code.devision(10 / 0)
    except Exception as e:
        logging.error("another error message.", extra=dict(error_param1='param1', error_param2='param2'))
        # capture_exception()
image.png

好在我们可以使用logging.error()方法报错,并通过extra参数添加额外的信息,方便我们debug.

上一篇 下一篇

猜你喜欢

热点阅读