python项目中集成sentry上报

登录注册

登录Sentry官网(https://sentry.io/)注册账号

创建项目

创建一个测试sentry项目
选择项目语言

在demo中可以得到自己的DSN

触发异常捕获上报

配置本地的客户端

首先通过 pip 安装 Sentry SDK

pip install raven --upgrade 

然后初始化客户端:

from raven import Client

DSN = 'https://****@sentry.io/****'
client = Client(DSN)

最后,在我们需要记录异常的代码处调用 client.captureException() 即可。

try:
    1 / 0
except ZeroDivisionError:
    client.captureException()

测试程序

很多时候我们的异常处理应该包含更多的上下文信息,这样对于我们做后续分析会有更多帮助 ,那么我们可以在sentry捕获异常之前加入这些上下文信息。

try:
    processing(user, data)

except:
    client.user_context({
        'user': user.email,
        'data': json.dumps(data)
    })
    client.captureException()

在框架之中嵌入 sentry

我们不可能在每一个可能发生异常代码的地方都调用 sentry,也不可能去修补过去的代码将 sentry 每一个去植入。一个好的建议是,无论何时,你的程序都有统一的异常处理机制,最好是全局的。这样的话,你只要将Sentry写在全局的异常处理器即可。
另外Sentry还对流行的开发框架提供了特别的支持,比如Flask,Django等等,在这些应用中你只要配置就行,不需要你去写什么全局的异常处理(虽然写起来也不难)。

Flask 的 demo

sentry = Sentry(dsn='http://public_key:[email protected]/1')

def create_app():
    app = Flask(__name__)
    sentry.init_app(app)
    return app

Django 的 demo

import os
import raven

INSTALLED_APPS = (
    'raven.contrib.django.raven_compat',
)

RAVEN_CONFIG = {
    'dsn': 'http://public_key:[email protected]/1',
    # If you are using git, you can also automatically 
    # configure the release based on the git info.
    'release': raven.fetch_git_sha(os.path.abspath(os.pardir)),
}

将 sentry 接入日志模块

接入代码示例:

import logging
import sentry_sdk
from sentry_sdk.integrations.logging import LoggingIntegration

# All of this is already happening by default!
sentry_logging = LoggingIntegration(
    level=logging.INFO,        # Capture info and above as breadcrumbs
    event_level=logging.ERROR  # Send errors as events
)
sentry_sdk.init(
    dsn="https://[email protected]/1501024",
    integrations=[sentry_logging]
)

logging.debug("I am ignored")
logging.info("I am a breadcrumb")
logging.error("I am an event", extra=dict(bar=43))
logging.error("An exception happened", exc_info=True)

在整个程序的多个 logger 中忽略某个 logger 不进行上报。

from sentry_sdk.integrations.logging import ignore_logger


ignore_logger("a.spammy.logger")

logger = logging.getLogger("a.spammy.logger")
logger.error("hi")  # no error sent to sentry

将 sentry 客户端接入 logging 配置

from raven.handlers.logging import SentryHandler

logger = logging.getLogger()
logger.addHandler(SentryHandler(level=logging.DEBUG, dsn="https://[email protected]/1501024"))

TODO: 有个问题,就是即使设置为了 level,只有 warning 形式的会被上报。

转载链接

https://segmentfault.com/a/1190000014847638

参考链接

https://blog.ansheng.me/article/docker-sentry-django-email-dingtalk/

https://docs.sentry.io/platforms/python/logging/

https://github.com/getsentry/sentry-python/issues/228

猜你喜欢

转载自blog.csdn.net/Enjolras_fuu/article/details/95315260