sentry-python-sdk
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSentry Python SDK
Sentry Python SDK
Opinionated wizard that scans your Python project and guides you through complete Sentry setup.
这是一个智能向导,会扫描你的Python项目并引导你完成完整的Sentry配置流程。
Invoke This Skill When
触发此技能的场景
- User asks to "add Sentry to Python" or "setup Sentry" in a Python app
- User wants error monitoring, tracing, profiling, logging, metrics, or crons in Python
- User mentions ,
sentry-sdk, or Sentry + any Python frameworksentry_sdk - User wants to monitor Django views, Flask routes, FastAPI endpoints, Celery tasks, or scheduled jobs
Note: SDK versions and APIs below reflect Sentry docs at time of writing (sentry-sdk 2.x). Always verify against docs.sentry.io/platforms/python/ before implementing.
- 用户要求「为Python添加Sentry」或在Python应用中「配置Sentry」
- 用户希望在Python中实现错误监控、链路追踪、性能剖析、日志收集、指标监控或定时任务监控
- 用户提及、
sentry-sdk或Sentry与任意Python框架的组合sentry_sdk - 用户希望监控Django视图、Flask路由、FastAPI接口、Celery任务或定时作业
注意: 以下SDK版本和API基于编写时的Sentry文档(sentry-sdk 2.x)。 实施前请务必参考Sentry官方Python平台文档进行验证。
Phase 1: Detect
阶段1:项目检测
Run these commands to understand the project before making recommendations:
bash
undefined运行以下命令了解项目情况,以便给出针对性建议:
bash
undefinedCheck existing Sentry
检查是否已存在Sentry
grep -i sentry requirements.txt pyproject.toml setup.cfg setup.py 2>/dev/null
grep -i sentry requirements.txt pyproject.toml setup.cfg setup.py 2>/dev/null
Detect web framework
检测Web框架
grep -rE "django|flask|fastapi|starlette|aiohttp|tornado|quart|falcon|sanic|bottle"
requirements.txt pyproject.toml 2>/dev/null
requirements.txt pyproject.toml 2>/dev/null
grep -rE "django|flask|fastapi|starlette|aiohttp|tornado|quart|falcon|sanic|bottle" \
requirements.txt pyproject.toml 2>/dev/null
Detect task queues
检测任务队列
grep -rE "celery|rq|huey|arq|dramatiq" requirements.txt pyproject.toml 2>/dev/null
grep -rE "celery|rq|huey|arq|dramatiq" requirements.txt pyproject.toml 2>/dev/null
Detect logging libraries
检测日志库
grep -E "loguru" requirements.txt pyproject.toml 2>/dev/null
grep -E "loguru" requirements.txt pyproject.toml 2>/dev/null
Detect AI libraries
检测AI库
grep -rE "openai|anthropic|langchain|huggingface|google-genai|pydantic-ai|litellm"
requirements.txt pyproject.toml 2>/dev/null
requirements.txt pyproject.toml 2>/dev/null
grep -rE "openai|anthropic|langchain|huggingface|google-genai|pydantic-ai|litellm" \
requirements.txt pyproject.toml 2>/dev/null
Detect schedulers / crons
检测调度器/定时任务
grep -rE "celery|apscheduler|schedule|crontab" requirements.txt pyproject.toml 2>/dev/null
grep -rE "celery|apscheduler|schedule|crontab" requirements.txt pyproject.toml 2>/dev/null
Check for companion frontend
检查是否存在配套前端
ls frontend/ web/ client/ ui/ static/ templates/ 2>/dev/null
**What to note:**
- Is `sentry-sdk` already in requirements? If yes, check if `sentry_sdk.init()` is present — may just need feature config.
- Which framework? (Determines where to place `sentry_sdk.init()`.)
- Which task queue? (Celery needs dual-process init; RQ needs a settings file.)
- AI libraries? (OpenAI, Anthropic, LangChain are auto-instrumented.)
- Companion frontend? (Triggers Phase 4 cross-link.)
---ls frontend/ web/ client/ ui/ static/ templates/ 2>/dev/null
**需要注意的点:**
- 项目依赖中是否已包含`sentry-sdk`?如果已存在,检查是否已调用`sentry_sdk.init()`——可能仅需配置功能模块。
- 项目使用的是哪种框架?(这将决定`sentry_sdk.init()`的放置位置。)
- 项目使用的是哪种任务队列?(Celery需要双进程初始化;RQ需要配置文件。)
- 是否包含AI库?(OpenAI、Anthropic、LangChain支持自动埋点。)
- 是否存在配套前端?(触发阶段4的跨端关联配置。)
---Phase 2: Recommend
阶段2:功能推荐
Based on what you found, present a concrete proposal. Don't ask open-ended questions — lead with a recommendation:
Always recommended (core coverage):
- ✅ Error Monitoring — captures unhandled exceptions, supports (Python 3.11+)
ExceptionGroup - ✅ Logging — Python stdlib auto-captured; enhanced if Loguru detected
logging
Recommend when detected:
- ✅ Tracing — HTTP framework detected (Django/Flask/FastAPI/etc.)
- ✅ AI Monitoring — OpenAI/Anthropic/LangChain/etc. detected (auto-instrumented, zero config)
- ⚡ Profiling — production apps where performance matters
- ⚡ Crons — Celery Beat, APScheduler, or cron patterns detected
- ⚡ Metrics — business KPIs, SLO tracking
Recommendation matrix:
| Feature | Recommend when... | Reference |
|---|---|---|
| Error Monitoring | Always — non-negotiable baseline | |
| Tracing | Django/Flask/FastAPI/AIOHTTP/etc. detected | |
| Profiling | Production + performance-sensitive workload | |
| Logging | Always (stdlib); enhanced for Loguru | |
| Metrics | Business events or SLO tracking needed | |
| Crons | Celery Beat, APScheduler, or cron patterns | |
| AI Monitoring | OpenAI/Anthropic/LangChain/etc. detected | |
Propose: "I recommend Error Monitoring + Tracing [+ Logging if applicable]. Want Profiling, Crons, or AI Monitoring too?"
根据检测结果,给出具体的配置方案。避免开放式问题,直接给出明确建议:
始终推荐的核心功能:
- ✅ 错误监控 —— 捕获未处理异常,支持Python 3.11+的
ExceptionGroup - ✅ 日志收集 —— 自动捕获Python标准库的日志;若检测到Loguru则提供增强支持
logging
检测到对应场景时推荐:
- ✅ 链路追踪 —— 检测到HTTP框架(Django/Flask/FastAPI等)
- ✅ AI监控 —— 检测到OpenAI/Anthropic/LangChain等AI库(自动埋点,无需额外配置)
- ⚡ 性能剖析 —— 生产环境中对性能敏感的应用
- ⚡ 定时任务监控 —— 检测到Celery Beat、APScheduler或cron表达式
- ⚡ 指标监控 —— 业务KPI追踪、SLO监控
推荐矩阵:
| 功能 | 推荐场景 | 参考文档 |
|---|---|---|
| 错误监控 | 始终推荐 —— 基础必备功能 | |
| 链路追踪 | 检测到Django/Flask/FastAPI/AIOHTTP等框架 | |
| 性能剖析 | 生产环境+对性能敏感的工作负载 | |
| 日志收集 | 始终推荐(标准库);Loguru环境下增强支持 | |
| 指标监控 | 需要追踪业务事件或SLO | |
| 定时任务监控 | 检测到Celery Beat、APScheduler或cron表达式 | |
| AI监控 | 检测到OpenAI/Anthropic/LangChain等AI库 | |
推荐话术示例:「我推荐配置错误监控+链路追踪[+日志收集(若适用)]。是否还需要配置性能剖析、定时任务监控或AI监控?」
Phase 3: Guide
阶段3:配置指导
Install
安装SDK
bash
undefinedbash
undefinedCore SDK (always required)
核心SDK(必须安装)
pip install sentry-sdk
pip install sentry-sdk
Optional extras (install only what matches detected framework):
可选扩展包(仅安装与检测到的框架匹配的包):
pip install "sentry-sdk[django]"
pip install "sentry-sdk[flask]"
pip install "sentry-sdk[fastapi]"
pip install "sentry-sdk[celery]"
pip install "sentry-sdk[aiohttp]"
pip install "sentry-sdk[tornado]"
pip install "sentry-sdk[django]"
pip install "sentry-sdk[flask]"
pip install "sentry-sdk[fastapi]"
pip install "sentry-sdk[celery]"
pip install "sentry-sdk[aiohttp]"
pip install "sentry-sdk[tornado]"
Multiple extras:
安装多个扩展包:
pip install "sentry-sdk[django,celery]"
> Extras are optional — plain `sentry-sdk` works for all frameworks. Extras install complementary packages.pip install "sentry-sdk[django,celery]"
> 扩展包为可选组件——基础`sentry-sdk`可支持所有框架。扩展包仅用于安装配套依赖。Quick Start — Recommended Init
快速开始——推荐初始化配置
Full init enabling the most features with sensible defaults. Place before any app/framework code:
python
import sentry_sdk
sentry_sdk.init(
dsn=os.environ["SENTRY_DSN"],
environment=os.environ.get("SENTRY_ENVIRONMENT", "production"),
release=os.environ.get("SENTRY_RELEASE"), # e.g. "myapp@1.0.0"
send_default_pii=True,
# Tracing (lower to 0.1–0.2 in high-traffic production)
traces_sample_rate=1.0,
# Profiling — continuous, tied to active spans
profile_session_sample_rate=1.0,
profile_lifecycle="trace",
# Structured logs (SDK ≥ 2.35.0)
enable_logs=True,
)以下是启用多数功能的完整初始化配置,附带合理默认值。请将代码放置在所有应用/框架代码之前:
python
import sentry_sdk
sentry_sdk.init(
dsn=os.environ["SENTRY_DSN"],
environment=os.environ.get("SENTRY_ENVIRONMENT", "production"),
release=os.environ.get("SENTRY_RELEASE"), # 示例:"myapp@1.0.0"
send_default_pii=True,
# 链路追踪(高流量生产环境可设置为0.1–0.2)
traces_sample_rate=1.0,
# 性能剖析——持续追踪,关联活跃链路
profile_session_sample_rate=1.0,
profile_lifecycle="trace",
# 结构化日志(SDK ≥ 2.35.0)
enable_logs=True,
)Where to Initialize Per Framework
各框架的初始化位置
| Framework | Where to call | Notes |
|---|---|---|
| Django | Top of | No middleware needed — Sentry patches Django internally |
| Flask | Before | Must precede app creation |
| FastAPI | Before | |
| Starlette | Before | Same auto-integration as FastAPI |
| AIOHTTP | Module level, before | |
| Tornado | Module level, before app setup | No integration class needed |
| Quart | Before | |
| Falcon | Module level, before | |
| Sanic | Inside | Sanic's lifecycle requires async init |
| Celery | | Dual-process init required |
| RQ | | |
| ARQ | Both worker module and enqueuing process |
Django example ():
settings.pypython
import sentry_sdk
sentry_sdk.init(
dsn=os.environ["SENTRY_DSN"],
send_default_pii=True,
traces_sample_rate=1.0,
profile_session_sample_rate=1.0,
profile_lifecycle="trace",
enable_logs=True,
)| 框架 | | 注意事项 |
|---|---|---|
| Django | | 无需配置中间件——Sentry会自动补丁Django内部逻辑 |
| Flask | 在 | 必须早于应用实例创建 |
| FastAPI | 在 | |
| Starlette | 在 | 与FastAPI的自动集成逻辑相同 |
| AIOHTTP | 模块级别,在 | |
| Tornado | 模块级别,在应用初始化之前 | 无需集成类 |
| Quart | 在 | |
| Falcon | 模块级别,在 | |
| Sanic | 在 | Sanic的生命周期要求异步初始化 |
| Celery | 工作进程中的 | 需要双进程初始化 |
| RQ | 工作进程通过 | |
| ARQ | 工作进程模块和任务提交进程中 |
Django示例():
settings.pypython
import sentry_sdk
sentry_sdk.init(
dsn=os.environ["SENTRY_DSN"],
send_default_pii=True,
traces_sample_rate=1.0,
profile_session_sample_rate=1.0,
profile_lifecycle="trace",
enable_logs=True,
)rest of Django settings...
Django其他配置...
INSTALLED_APPS = [...]
**FastAPI example** (`main.py`):
```python
import sentry_sdk
sentry_sdk.init(
dsn=os.environ["SENTRY_DSN"],
send_default_pii=True,
traces_sample_rate=1.0,
profile_session_sample_rate=1.0,
profile_lifecycle="trace",
enable_logs=True,
)
from fastapi import FastAPI
app = FastAPI()INSTALLED_APPS = [...]
**FastAPI示例**(`main.py`):
```python
import sentry_sdk
sentry_sdk.init(
dsn=os.environ["SENTRY_DSN"],
send_default_pii=True,
traces_sample_rate=1.0,
profile_session_sample_rate=1.0,
profile_lifecycle="trace",
enable_logs=True,
)
from fastapi import FastAPI
app = FastAPI()Auto-Enabled vs Explicit Integrations
自动启用与显式集成
Most integrations activate automatically when their package is installed — no needed:
integrations=[...]| Auto-enabled | Explicit required |
|---|---|
| Django, Flask, FastAPI, Starlette, AIOHTTP, Tornado, Quart, Falcon, Sanic, Bottle | |
| Celery, RQ, Huey, ARQ | |
| SQLAlchemy, Redis, asyncpg, pymongo | |
| Requests, HTTPX, aiohttp-client | |
| OpenAI, Anthropic, LangChain, Pydantic AI, MCP | |
Python | |
多数集成会在对应包安装后自动激活——无需配置:
integrations=[...]| 自动启用 | 需要显式配置 |
|---|---|
| Django、Flask、FastAPI、Starlette、AIOHTTP、Tornado、Quart、Falcon、Sanic、Bottle | |
| Celery、RQ、Huey、ARQ | |
| SQLAlchemy、Redis、asyncpg、pymongo | |
| Requests、HTTPX、aiohttp-client | |
| OpenAI、Anthropic、LangChain、Pydantic AI、MCP | |
Python | |
For Each Agreed Feature
逐个配置已确认的功能
Walk through features one at a time. Load the reference, follow its steps, verify before moving on:
| Feature | Reference file | Load when... |
|---|---|---|
| Error Monitoring | | Always (baseline) |
| Tracing | | HTTP handlers / distributed tracing |
| Profiling | | Performance-sensitive production |
| Logging | | Always; enhanced for Loguru |
| Metrics | | Business KPIs / SLO tracking |
| Crons | | Scheduler / cron patterns detected |
| AI Monitoring | | AI library detected |
For each feature: , follow steps exactly, verify it works.
Read ${SKILL_ROOT}/references/<feature>.md逐个配置用户确认的功能。加载对应参考文档,按照步骤操作,验证完成后再进行下一项:
| 功能 | 参考文件 | 加载时机 |
|---|---|---|
| 错误监控 | | 始终加载(基础功能) |
| 链路追踪 | | 存在HTTP处理器/分布式追踪需求时 |
| 性能剖析 | | 生产环境且对性能敏感的工作负载 |
| 日志收集 | | 始终加载;Loguru环境下增强配置 |
| 指标监控 | | 需要追踪业务KPI/SLO时 |
| 定时任务监控 | | 检测到调度器/cron表达式时 |
| AI监控 | | 检测到AI库时 |
对于每个功能:读取,严格按照步骤操作,验证功能正常运行。
${SKILL_ROOT}/references/<feature>.mdConfiguration Reference
配置参数参考
Key sentry_sdk.init()
Options
sentry_sdk.init()sentry_sdk.init()
的关键参数
sentry_sdk.init()| Option | Type | Default | Purpose |
|---|---|---|---|
| | | SDK disabled if empty; env: |
| | | e.g., |
| | | e.g., |
| | | Include IP, headers, cookies, auth user |
| | | Transaction sample rate; |
| | | Custom per-transaction sampling (overrides rate) |
| | | Continuous profiling session rate |
| | | |
| | | Transaction-based profiling rate |
| | | Send logs to Sentry (SDK ≥ 2.35.0) |
| | | Error event sample rate |
| | | Stack traces on |
| | | Max breadcrumbs per event |
| | | Verbose SDK debug output |
| | | Hook to mutate/drop error events |
| | | Hook to mutate/drop transaction events |
| | | Exception types or regex patterns to suppress |
| | | Set |
| 参数 | 类型 | 默认值 | 用途 |
|---|---|---|---|
| | | 若为空则SDK禁用;可通过环境变量 |
| | | 示例: |
| | | 示例: |
| | | 是否包含IP、请求头、Cookie、认证用户等隐私数据 |
| | | 链路追踪采样率; |
| | | 自定义链路追踪采样逻辑(优先级高于采样率) |
| | | 持续性能剖析会话采样率 |
| | | 设置为 |
| | | 基于链路追踪的性能剖析采样率 |
| | | 将日志发送至Sentry(需SDK ≥ 2.35.0) |
| | | 错误事件采样率 |
| | | 调用 |
| | | 每个事件的最大面包屑数量 |
| | | 是否启用SDK详细调试输出 |
| | | 错误事件发送前的钩子函数,可修改或丢弃事件 |
| | | 链路追踪事件发送前的钩子函数,可修改或丢弃事件 |
| | | 需要忽略的异常类型或正则表达式 |
| | | 设置为 |
Environment Variables
环境变量
| Variable | Maps to | Notes |
|---|---|---|
| | |
| | Also auto-detected from git SHA, Heroku, CircleCI, CodeBuild, GAE |
| | |
| |
| 环境变量 | 对应参数 | 说明 |
|---|---|---|
| | |
| | 也可从Git SHA、Heroku、CircleCI、CodeBuild、GAE自动检测 |
| | |
| |
Verification
验证配置
Test that Sentry is receiving events:
python
undefined测试Sentry是否正常接收事件:
python
undefinedTrigger a real error event — check dashboard within seconds
触发真实错误事件——几秒内即可在控制台查看
division_by_zero = 1 / 0
Or for a non-crashing check:
```python
sentry_sdk.capture_message("Sentry Python SDK test")If nothing appears:
- Set in
debug=True— prints SDK internals to stdoutsentry_sdk.init() - Verify the DSN is correct
- Check env var is set in the running process
SENTRY_DSN - For Celery/RQ: ensure init runs in the worker process, not just the calling process
division_by_zero = 1 / 0
或使用非崩溃式测试:
```python
sentry_sdk.capture_message("Sentry Python SDK 测试")若未收到事件:
- 在中设置
sentry_sdk.init()——将SDK内部日志输出至标准输出debug=True - 验证DSN是否正确
- 确认运行进程中已设置环境变量
SENTRY_DSN - 对于Celery/RQ:确保初始化代码在工作进程中运行,而非仅在调用进程中
Phase 4: Cross-Link
阶段4:跨端关联配置
After completing Python setup, check for a companion frontend missing Sentry:
bash
ls frontend/ web/ client/ ui/ 2>/dev/null
cat frontend/package.json web/package.json client/package.json 2>/dev/null \
| grep -E '"react"|"svelte"|"vue"|"next"|"nuxt"'If a frontend exists without Sentry, suggest the matching skill:
| Frontend detected | Suggest skill |
|---|---|
| React / Next.js | |
| Svelte / SvelteKit | |
| Vue / Nuxt | Use |
| Other JS/TS | |
完成Python端配置后,检查是否存在未配置Sentry的配套前端:
bash
ls frontend/ web/ client/ ui/ 2>/dev/null
cat frontend/package.json web/package.json client/package.json 2>/dev/null \\
| grep -E '"react"|"svelte"|"vue"|"next"|"nuxt"'若存在未配置Sentry的前端,推荐使用对应技能:
| 检测到的前端 | 推荐技能 |
|---|---|
| React / Next.js | |
| Svelte / SvelteKit | |
| Vue / Nuxt | 使用 |
| 其他JS/TS框架 | |
Troubleshooting
问题排查
| Issue | Solution |
|---|---|
| Events not appearing | Set |
| Malformed DSN error | Format: |
| Django exceptions not captured | Ensure |
| Flask exceptions not captured | Init must happen before |
| FastAPI exceptions not captured | Init before |
| Celery task errors not captured | Must call |
| Sanic init not working | Init must be inside |
| uWSGI not capturing | Add |
| No traces appearing | Verify |
| Profiling not starting | Requires |
| Requires SDK ≥ 2.35.0; for direct structured logs use |
| Too many transactions | Lower |
| Cross-request data leaking | Don't use |
| RQ worker not reporting | Pass |
| 问题 | 解决方案 |
|---|---|
| 事件未出现在控制台 | 设置 |
| DSN格式错误 | 正确格式: |
| Django异常未被捕获 | 确保 |
| Flask异常未被捕获 | 初始化必须在 |
| FastAPI异常未被捕获 | 初始化在 |
| Celery任务错误未被捕获 | 必须通过 |
| Sanic初始化失败 | 初始化必须在 |
| uWSGI未捕获事件 | 在uWSGI命令中添加 |
| 无链路追踪数据 | 确保 |
| 性能剖析未启动 | 需要 |
| 需SDK ≥ 2.35.0;直接发送结构化日志使用 |
| 链路追踪事件过多 | 降低 |
| 请求间数据泄露 | 不要使用 |
| RQ工作进程未上报事件 | 传递 |
| ", |