Sentry错误监控 — Sentry应用错误追踪
一句话概述:Sentry 是最流行的应用错误监控平台,你的程序一旦出错,Sentry 立刻通知你并告诉你错在哪、谁触发的、当时的上下文是什么,帮你快速定位和修复 Bug。
核心知识点速查表
| 概念 | 白话解释 |
|---|
| Issue | 一组相同的错误被归为一个 Issue |
| Event | 每次错误发生就是一个 Event |
| Breadcrumbs | 面包屑,错误发生前用户做了什么操作的记录 |
| Stack Trace | 调用栈,显示错误发生在哪行代码 |
| Release | 版本,追踪哪个版本引入了新 Bug |
| DSN | 数据源名称,连接你的程序和 Sentry 的密钥 |
当前版本信息(2026年)
| 信息 | 详情 |
|---|
| 支持语言 | Python、JavaScript、Java、Go、Ruby、PHP、.NET、Rust 等 |
| 部署方式 | 云服务(sentry.io)或 自托管 |
| 新功能 | Structured Logging(2025年5月 Beta) |
| 用户规模 | 100,000+ 组织 |
| 估值 | $30亿(2022年) |
| 官网 | https://sentry.io |
安装配置
Python 项目集成
# 安装 Sentry SDK
pip install sentry-sdk
# 如果用 Flask/Django/FastAPI,安装对应集成
pip install sentry-sdk[flask]
pip install sentry-sdk[django]
pip install sentry-sdk[fastapi]
初始化 Sentry
# app.py 或 main.py(在应用启动时初始化)
import sentry_sdk
sentry_sdk.init(
dsn="https://xxx@xxx.ingest.sentry.io/xxx", # 从 Sentry 项目设置获取
traces_sample_rate=1.0, # 性能监控采样率(1.0=100%)
profiles_sample_rate=1.0, # 性能分析采样率
environment="production", # 环境标识
release="my-app@1.0.0", # 版本号
send_default_pii=False, # 不发送个人信息(GDPR)
)
# DSN 从哪里获取?
# 1. 登录 sentry.io
# 2. 创建项目(选择 Python)
# 3. 在 Settings → Client Keys 中找到 DSN
框架集成示例
# Flask 集成
import sentry_sdk
from flask import Flask
sentry_sdk.init(dsn="https://xxx@xxx.ingest.sentry.io/xxx")
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello!"
@app.route("/error")
def error():
1 / 0 # 这个错误会自动上报到 Sentry
# Django 集成 — settings.py
import sentry_sdk
sentry_sdk.init(
dsn="https://xxx@xxx.ingest.sentry.io/xxx",
traces_sample_rate=1.0,
)
# FastAPI 集成
import sentry_sdk
from fastapi import FastAPI
sentry_sdk.init(dsn="https://xxx@xxx.ingest.sentry.io/xxx")
app = FastAPI()
基本使用
手动捕获错误
import sentry_sdk
# 捕获异常
try:
result = dangerous_operation() # 可能出错的操作
except Exception as e:
sentry_sdk.capture_exception(e) # 手动上报异常
# 发送消息(不是错误,只是通知)
sentry_sdk.capture_message("用户尝试访问被禁的页面")
# 添加上下文信息
sentry_sdk.set_user({"id": "123", "email": "user@example.com"}) # 用户信息
sentry_sdk.set_tag("page", "/settings") # 标签
sentry_sdk.set_context("order", {"id": "456", "amount": 99.9}) # 自定义上下文
# 面包屑(记录操作步骤)
sentry_sdk.add_breadcrumb(
category="auth", # 分类
message="用户登录成功", # 描述
level="info", # 级别
)
性能监控
import sentry_sdk
# 手动创建事务(追踪某个操作的耗时)
with sentry_sdk.start_transaction(op="task", name="process_data") as txn:
with txn.start_child(op="db", description="查询数据库") as span:
data = query_database() # 数据库查询
with txn.start_child(op="compute", description="数据处理") as span:
result = process(data) # 数据处理
with txn.start_child(op="http", description="调用外部API") as span:
response = call_api(result) # 外部调用
# Sentry 会自动追踪:
# - HTTP 请求的响应时间
# - 数据库查询耗时
# - 外部 API 调用耗时
结构化日志(2025+ 新功能)
import sentry_sdk
import logging
# 启用日志集成
sentry_sdk.init(
dsn="...",
_experiments={
"enable_logs": True, # 启用结构化日志(Beta)
},
)
# 正常使用 logging,日志会自动发送到 Sentry
logger = logging.getLogger(__name__)
logger.info("处理订单", extra={"order_id": "123"})
logger.error("支付失败", extra={"error_code": "TIMEOUT"})
高级用法
忽略特定错误
sentry_sdk.init(
dsn="...",
ignore_errors=[
KeyboardInterrupt, # 忽略 Ctrl+C
ConnectionResetError, # 忽略连接重置
],
before_send=lambda event, hint: None if "ignore" in str(hint.get("exc_info", "")) else event,
)
Release 追踪
sentry_sdk.init(
dsn="...",
release="my-app@1.2.3", # 设置版本号
)
# 好处:
# 1. 知道哪个版本引入了新 Bug
# 2. 发布后监控新增错误
# 3. 关联 Git commit(知道是哪次提交导致的)
告警配置
# 在 Sentry Web UI 中设置告警:
# Alerts → Create Alert Rule
# 条件示例:
# - 同一错误在 5 分钟内出现 10 次 → 发邮件/Slack
# - 新错误首次出现 → 立即通知
# - 某个错误的用户数超过 100 → 紧急通知
自托管部署
# 使用官方 Docker Compose 自托管
git clone https://github.com/getsentry/self-hosted.git
cd self-hosted
./install.sh # 安装并启动
# 访问 http://localhost:9000
# 自托管适合:
# - 数据安全要求高(数据不出内网)
# - 大量事件(避免云端费用)
# - 需要自定义的场景
常见报错与解决
| 问题 | 原因 | 解决方案 |
|---|
| 错误没上报 | DSN 配置错误 | 检查 DSN 字符串是否正确 |
| 重复错误太多 | 没有聚合 | Sentry 自动聚合,检查 fingerprint |
| 性能数据为空 | 采样率为0 | 设置 traces_sample_rate=1.0 |
| 事件被丢弃 | 超出配额 | 升级套餐或调低采样率 |
| 敏感信息泄露 | PII 未过滤 | send_default_pii=False + before_send 过滤 |
| SDK 初始化失败 | 网络不通 | 检查防火墙,确认能访问 sentry.io |
速查表
# ===== 初始化 =====
sentry_sdk.init(dsn="...") # 基本初始化
sentry_sdk.init(dsn="...", environment="prod", release="v1.0") # 完整初始化
# ===== 错误上报 =====
sentry_sdk.capture_exception(e) # 上报异常
sentry_sdk.capture_message("msg") # 上报消息
# ===== 上下文 =====
sentry_sdk.set_user({"id": "123"}) # 设置用户
sentry_sdk.set_tag("key", "value") # 设置标签
sentry_sdk.set_context("name", {}) # 设置上下文
sentry_sdk.add_breadcrumb(message="...") # 添加面包屑
# ===== 性能 =====
with sentry_sdk.start_transaction(name="..") as txn: # 事务
with txn.start_child(op="..") as span: # 子操作
pass
同类工具对比
| 特性 | Sentry | GlitchTip | Rollbar | Datadog |
|---|
| 错误追踪 | ✅ 强大 | ✅ | ✅ | ✅ |
| 性能监控 | ✅ | ❌ | ❌ | ✅ 更强 |
| Session Replay | ✅ | ❌ | ❌ | ✅ |
| 开源自托管 | ✅ | ✅(轻量) | ❌ | ❌ |
| 免费额度 | 5K 事件/月 | 自托管无限 | 5K/月 | 14天试用 |
| SDK 质量 | 优秀 | 复用 Sentry | 好 | 好 |
| 价格(付费) | $26/月起 | 免费 | $24/月 | $15/月起 |
总结:Sentry 是错误监控领域的标杆,特别适合 Web 应用和后端服务。免费版 5000 事件/月对小项目够用。如果预算有限且需要更多事件量,可以考虑自托管 Sentry 或使用 GlitchTip(Sentry 的开源替代)。