You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Sentry捕获Python运行时抛出的各类警告信息

Sentry 捕获 Python 运行时警告的实现方案

Sentry SDK 默认不会自动捕获 Python warnings 模块抛出的警告内容,你需要手动调整初始化配置开启对应能力:

  • 初始化 Sentry SDK 时添加 capture_warnings=True 配置项即可开启自动捕获,示例代码如下:
import sentry_sdk
import warnings

sentry_sdk.init(
    dsn="你的 Sentry 项目 DSN",
    # 开启警告捕获开关
    capture_warnings=True,
    # 保留你原有其他初始化配置即可
)
  • 开启后所有通过 warnings.warn() 触发的警告,包括你提到的 DeprecationWarning、RuntimeWarning 等内置警告类型,都会自动作为 warning 级别的事件上报到 Sentry,和异常事件区分展示。
  • 如果你需要自定义警告上报的过滤规则,可以搭配 before_send 钩子实现,比如只上报 DeprecationWarning 忽略其他警告的示例如下:
def before_send(event, hint):
    # 过滤非 DeprecationWarning 类型的警告
    if "log_record" in hint:
        record = hint["log_record"]
        if record.levelname == "WARNING" and len(record.args) > 0:
            if getattr(record.args[0], "__class__", object).__name__ != "DeprecationWarning":
                return None
    return event

sentry_sdk.init(
    dsn="你的 Sentry 项目 DSN",
    capture_warnings=True,
    before_send=before_send
)

注意:如果你的项目中已经通过 warnings.filterwarnings("ignore") 配置了全局忽略某类警告,这类被 Python 运行时过滤掉的警告无法被 Sentry 捕获,需要先调整警告过滤规则保证目标警告能被正常触发。

内容的提问来源于stack exchange,提问作者azmeuk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 19:24:04