sentry-python-sdk by getsentry/sentry-agent-skills
npx skills add https://github.com/getsentry/sentry-agent-skills --skill sentry-python-sdk一款智能向导,可扫描您的 Python 项目并指导您完成完整的 Sentry 设置。
sentry-sdk、sentry_sdk 或 Sentry + 任何 Python 框架注意: 下面的 SDK 版本和 API 反映了撰写时的 Sentry 文档(sentry-sdk 2.x)。在实施前,请务必根据 docs.sentry.io/platforms/python/ 进行验证。
在提出建议之前,运行以下命令来了解项目情况:
# 检查现有 Sentry
grep -i sentry requirements.txt pyproject.toml setup.cfg setup.py 2>/dev/null
# 检测 Web 框架
grep -rE "django|flask|fastapi|starlette|aiohttp|tornado|quart|falcon|sanic|bottle" \
requirements.txt pyproject.toml 2>/dev/null
# 检测任务队列
grep -rE "celery|rq|huey|arq|dramatiq" requirements.txt pyproject.toml 2>/dev/null
# 检测日志库
grep -E "loguru" requirements.txt pyproject.toml 2>/dev/null
# 检测 AI 库
grep -rE "openai|anthropic|langchain|huggingface|google-genai|pydantic-ai|litellm" \
requirements.txt pyproject.toml 2>/dev/null
# 检测调度器 / 定时任务
grep -rE "celery|apscheduler|schedule|crontab" requirements.txt pyproject.toml 2>/dev/null
# 检查配套前端
ls frontend/ web/ client/ ui/ static/ templates/ 2>/dev/null
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
需要注意的事项:
sentry-sdk 是否已在 requirements 中?如果是,检查 sentry_sdk.init() 是否存在 —— 可能只需要配置功能。sentry_sdk.init() 的放置位置。)根据您的发现,提出具体建议。不要问开放式问题 —— 直接给出推荐方案:
始终推荐(核心覆盖):
ExceptionGroup(Python 3.11+)logging 标准库;如果检测到 Loguru 则增强检测到时推荐:
推荐矩阵:
| 功能 | 推荐时机... | 参考文档 |
|---|---|---|
| 错误监控 | 始终 — 不可或缺的基线 | ${SKILL_ROOT}/references/error-monitoring.md |
| 追踪 | 检测到 Django/Flask/FastAPI/AIOHTTP/等 | ${SKILL_ROOT}/references/tracing.md |
| 性能剖析 | 生产环境 + 性能敏感型工作负载 | ${SKILL_ROOT}/references/profiling.md |
| 日志记录 | 始终(标准库);针对 Loguru 增强 | ${SKILL_ROOT}/references/logging.md |
| 指标 | 需要业务事件或 SLO 跟踪 | ${SKILL_ROOT}/references/metrics.md |
| 定时任务 | Celery Beat、APScheduler 或定时任务模式 | ${SKILL_ROOT}/references/crons.md |
| AI 监控 | 检测到 OpenAI/Anthropic/LangChain/等 | ${SKILL_ROOT}/references/ai-monitoring.md |
建议:"我推荐错误监控 + 追踪 [+ 日志记录(如适用)]。还需要性能剖析、定时任务或 AI 监控吗?"
# 核心 SDK(始终需要)
pip install sentry-sdk
# 可选扩展(仅安装与检测到的框架匹配的):
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,celery]"
扩展是可选的 —— 普通的
sentry-sdk适用于所有框架。扩展会安装补充包。
启用最多功能且具有合理默认值的完整初始化。将其放在任何应用/框架代码之前:
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,
# 性能剖析 — 连续的,与活跃的 span 绑定
profile_session_sample_rate=1.0,
profile_lifecycle="trace",
# 结构化日志(SDK ≥ 2.35.0)
enable_logs=True,
)
| 框架 | 调用 sentry_sdk.init() 的位置 | 备注 |
|---|---|---|
| Django | settings.py 顶部,在任何导入之前 | 不需要中间件 —— Sentry 在内部修补 Django |
| Flask | 在 app = Flask(__name__) 之前 | 必须在应用创建之前 |
| FastAPI | 在 app = FastAPI() 之前 | StarletteIntegration + FastApiIntegration 自动一起启用 |
| Starlette | 在 app = Starlette(...) 之前 | 与 FastAPI 相同的自动集成 |
| AIOHTTP | 模块级别,在 web.Application() 之前 | |
| Tornado | 模块级别,在应用设置之前 | 不需要集成类 |
| Quart | 在 app = Quart(__name__) 之前 | |
| Falcon | 模块级别,在 app = falcon.App() 之前 | |
| Sanic | 在 @app.listener("before_server_start") 内部 | Sanic 的生命周期需要异步初始化 |
| Celery | 工作进程和调用进程中的 @signals.celeryd_init.connect | 需要双进程初始化 |
| RQ | 通过 rq worker -c mysettings 加载的 mysettings.py | |
| ARQ | 工作模块和入队进程都需要 |
Django 示例(settings.py):
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 设置...
INSTALLED_APPS = [...]
FastAPI 示例(main.py):
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()
大多数集成在安装其包时会自动激活 —— 不需要 integrations=[...]:
| 自动启用 | 需要显式指定 |
|---|---|
| Django, Flask, FastAPI, Starlette, AIOHTTP, Tornado, Quart, Falcon, Sanic, Bottle | DramatiqIntegration |
| Celery, RQ, Huey, ARQ | GRPCIntegration |
| SQLAlchemy, Redis, asyncpg, pymongo | StrawberryIntegration |
| Requests, HTTPX, aiohttp-client | AsyncioIntegration |
| OpenAI, Anthropic, LangChain, Pydantic AI, MCP | OpenTelemetryIntegration |
Python logging, Loguru | WSGIIntegration / ASGIIntegration |
逐个功能进行指导。加载参考文档,按照其步骤操作,在继续之前进行验证:
| 功能 | 参考文件 | 加载时机... |
|---|---|---|
| 错误监控 | ${SKILL_ROOT}/references/error-monitoring.md | 始终(基线) |
| 追踪 | ${SKILL_ROOT}/references/tracing.md | HTTP 处理器 / 分布式追踪 |
| 性能剖析 | ${SKILL_ROOT}/references/profiling.md | 性能敏感的生产环境 |
| 日志记录 | ${SKILL_ROOT}/references/logging.md | 始终;针对 Loguru 增强 |
| 指标 | ${SKILL_ROOT}/references/metrics.md | 业务 KPI / SLO 跟踪 |
| 定时任务 | ${SKILL_ROOT}/references/crons.md | 检测到调度器 / 定时任务模式 |
| AI 监控 | ${SKILL_ROOT}/references/ai-monitoring.md | 检测到 AI 库 |
对于每个功能:Read ${SKILL_ROOT}/references/<feature>.md,严格按照步骤操作,验证其是否工作。
sentry_sdk.init() 选项| 选项 | 类型 | 默认值 | 用途 |
|---|---|---|---|
dsn | str | None | 如果为空则禁用 SDK;环境变量:SENTRY_DSN |
environment | str | "production" | 例如 "staging";环境变量:SENTRY_ENVIRONMENT |
release | str | None | 例如 "myapp@1.0.0";环境变量:SENTRY_RELEASE |
send_default_pii | bool | False | 包含 IP、请求头、Cookie、认证用户 |
traces_sample_rate | float | None | 事务采样率;None 禁用追踪 |
traces_sampler | Callable | None | 自定义每事务采样(覆盖采样率) |
profile_session_sample_rate | float | None | 连续性能剖析会话率 |
profile_lifecycle | str | "manual" | "trace" = 随 span 自动启动剖析器 |
profiles_sample_rate | float | None | 基于事务的剖析采样率 |
enable_logs | bool | False | 将日志发送到 Sentry(SDK ≥ 2.35.0) |
sample_rate | float | 1.0 | 错误事件采样率 |
attach_stacktrace | bool | False | 在 capture_message() 上附加堆栈跟踪 |
max_breadcrumbs | int | 100 | 每个事件的最大面包屑数 |
debug | bool | False | 详细的 SDK 调试输出 |
before_send | Callable | None | 用于修改/丢弃错误事件的钩子 |
before_send_transaction | Callable | None | 用于修改/丢弃事务事件的钩子 |
ignore_errors | list | [] | 要抑制的异常类型或正则表达式模式 |
auto_enabling_integrations | bool | True | 设置为 False 以禁用所有自动检测 |
| 变量 | 映射到 | 备注 |
|---|---|---|
SENTRY_DSN | dsn | |
SENTRY_RELEASE | release | 也会从 git SHA、Heroku、CircleCI、CodeBuild、GAE 自动检测 |
SENTRY_ENVIRONMENT | environment | |
SENTRY_DEBUG | debug |
测试 Sentry 是否正在接收事件:
# 触发一个真实的错误事件 — 在几秒钟内检查仪表板
division_by_zero = 1 / 0
或者进行非崩溃性检查:
sentry_sdk.capture_message("Sentry Python SDK 测试")
如果没有显示任何内容:
sentry_sdk.init() 中设置 debug=True — 将 SDK 内部信息打印到标准输出SENTRY_DSN 环境变量是否已设置完成 Python 设置后,检查配套前端是否缺少 Sentry:
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 | sentry-react-sdk |
| Svelte / SvelteKit | sentry-svelte-sdk |
| Vue / Nuxt | 使用 @sentry/vue — 参见 docs.sentry.io/platforms/javascript/guides/vue/ |
| 其他 JS/TS | sentry-react-sdk(涵盖通用的浏览器 JS 模式) |
| 问题 | 解决方案 |
|---|---|
| 事件未出现 | 设置 debug=True,验证 DSN,检查运行进程中的环境变量 |
| DSN 格式错误 | 格式:https://<key>@o<org>.ingest.sentry.io/<project> |
| Django 异常未捕获 | 确保 sentry_sdk.init() 在 settings.py 的顶部,在其他导入之前 |
| Flask 异常未捕获 | 初始化必须在 app = Flask(__name__) 之前 |
| FastAPI 异常未捕获 | 在 app = FastAPI() 之前初始化;StarletteIntegration 和 FastApiIntegration 都会自动启用 |
| Celery 任务错误未捕获 | 必须通过 celeryd_init 信号在工作进程中调用 sentry_sdk.init() |
| Sanic 初始化不工作 | 初始化必须在 @app.listener("before_server_start") 内部,而不是模块级别 |
| uWSGI 未捕获 | 在 uWSGI 命令中添加 --enable-threads --py-call-uwsgi-fork-hooks |
| 追踪未出现 | 验证 traces_sample_rate 已设置(不是 None);检查集成是否自动启用 |
| 性能剖析未启动 | 需要 traces_sample_rate > 0 + 设置 profile_session_sample_rate 或 profiles_sample_rate |
enable_logs 不工作 | 需要 SDK ≥ 2.35.0;对于直接的结构化日志使用 sentry_sdk.logger;对于标准库桥接使用 LoggingIntegration(sentry_logs_level=...) |
| 事务过多 | 降低 traces_sample_rate 或使用 traces_sampler 丢弃健康检查 |
| 跨请求数据泄漏 | 不要使用 get_global_scope() 存储每个请求的数据 —— 使用 get_isolation_scope() |
| RQ 工作进程未报告 | 传递 --sentry-dsn="" 以禁用 RQ 自身的 Sentry 快捷方式;改为通过设置文件初始化 |
每周安装量
75
代码仓库
GitHub 星标数
19
首次出现
2026年2月26日
安全审计
安装于
codex72
cursor70
gemini-cli69
opencode69
github-copilot68
amp68
Opinionated wizard that scans your Python project and guides you through complete Sentry setup.
sentry-sdk, sentry_sdk, or Sentry + any Python frameworkNote: 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.
Run these commands to understand the project before making recommendations:
# Check existing Sentry
grep -i sentry requirements.txt pyproject.toml setup.cfg setup.py 2>/dev/null
# Detect web framework
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
# Detect logging libraries
grep -E "loguru" requirements.txt pyproject.toml 2>/dev/null
# Detect AI libraries
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
# Check for companion frontend
ls frontend/ web/ client/ ui/ static/ templates/ 2>/dev/null
What to note:
sentry-sdk already in requirements? If yes, check if sentry_sdk.init() is present — may just need feature config.sentry_sdk.init().)Based on what you found, present a concrete proposal. Don't ask open-ended questions — lead with a recommendation:
Always recommended (core coverage):
ExceptionGroup (Python 3.11+)logging stdlib auto-captured; enhanced if Loguru detectedRecommend when detected:
Recommendation matrix:
| Feature | Recommend when... | Reference |
|---|---|---|
| Error Monitoring | Always — non-negotiable baseline | ${SKILL_ROOT}/references/error-monitoring.md |
| Tracing | Django/Flask/FastAPI/AIOHTTP/etc. detected | ${SKILL_ROOT}/references/tracing.md |
| Profiling | Production + performance-sensitive workload | ${SKILL_ROOT}/references/profiling.md |
| Logging | Always (stdlib); enhanced for Loguru | ${SKILL_ROOT}/references/logging.md |
| Metrics | Business events or SLO tracking needed |
Propose: "I recommend Error Monitoring + Tracing [+ Logging if applicable]. Want Profiling, Crons, or AI Monitoring too?"
# Core SDK (always required)
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]"
# Multiple extras:
pip install "sentry-sdk[django,celery]"
Extras are optional — plain
sentry-sdkworks for all frameworks. Extras install complementary packages.
Full init enabling the most features with sensible defaults. Place before any app/framework code:
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,
)
| Framework | Where to call sentry_sdk.init() | Notes |
|---|---|---|
| Django | Top of settings.py, before any imports | No middleware needed — Sentry patches Django internally |
| Flask | Before app = Flask(__name__) | Must precede app creation |
| FastAPI | Before app = FastAPI() | StarletteIntegration + FastApiIntegration auto-enabled together |
Django example (settings.py):
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...
INSTALLED_APPS = [...]
FastAPI example (main.py):
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()
Most integrations activate automatically when their package is installed — no integrations=[...] needed:
| Auto-enabled | Explicit required |
|---|---|
| Django, Flask, FastAPI, Starlette, AIOHTTP, Tornado, Quart, Falcon, Sanic, Bottle | DramatiqIntegration |
| Celery, RQ, Huey, ARQ | GRPCIntegration |
| SQLAlchemy, Redis, asyncpg, pymongo | StrawberryIntegration |
| Requests, HTTPX, aiohttp-client | AsyncioIntegration |
| OpenAI, Anthropic, LangChain, Pydantic AI, MCP | OpenTelemetryIntegration |
Python logging, Loguru |
Walk through features one at a time. Load the reference, follow its steps, verify before moving on:
| Feature | Reference file | Load when... |
|---|---|---|
| Error Monitoring | ${SKILL_ROOT}/references/error-monitoring.md | Always (baseline) |
| Tracing | ${SKILL_ROOT}/references/tracing.md | HTTP handlers / distributed tracing |
| Profiling | ${SKILL_ROOT}/references/profiling.md | Performance-sensitive production |
| Logging | ${SKILL_ROOT}/references/logging.md | Always; enhanced for Loguru |
| Metrics | ${SKILL_ROOT}/references/metrics.md |
For each feature: Read ${SKILL_ROOT}/references/<feature>.md, follow steps exactly, verify it works.
sentry_sdk.init() Options| Option | Type | Default | Purpose |
|---|---|---|---|
dsn | str | None | SDK disabled if empty; env: SENTRY_DSN |
environment | str | "production" | e.g., "staging"; env: |
| Variable | Maps to | Notes |
|---|---|---|
SENTRY_DSN | dsn | |
SENTRY_RELEASE | release | Also auto-detected from git SHA, Heroku, CircleCI, CodeBuild, GAE |
SENTRY_ENVIRONMENT | environment | |
SENTRY_DEBUG |
Test that Sentry is receiving events:
# Trigger a real error event — check dashboard within seconds
division_by_zero = 1 / 0
Or for a non-crashing check:
sentry_sdk.capture_message("Sentry Python SDK test")
If nothing appears:
debug=True in sentry_sdk.init() — prints SDK internals to stdoutSENTRY_DSN env var is set in the running processAfter completing Python setup, check for a companion frontend missing Sentry:
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 | sentry-react-sdk |
| Svelte / SvelteKit | sentry-svelte-sdk |
| Vue / Nuxt | Use @sentry/vue — see docs.sentry.io/platforms/javascript/guides/vue/ |
| Other JS/TS | sentry-react-sdk (covers generic browser JS patterns) |
| Issue | Solution |
|---|---|
| Events not appearing | Set debug=True, verify DSN, check env vars in the running process |
| Malformed DSN error | Format: https://<key>@o<org>.ingest.sentry.io/<project> |
| Django exceptions not captured | Ensure sentry_sdk.init() is at the top of settings.py before other imports |
| Flask exceptions not captured | Init must happen before app = Flask(__name__) |
| FastAPI exceptions not captured | Init before app = FastAPI(); both and auto-enabled |
Weekly Installs
75
Repository
GitHub Stars
19
First Seen
Feb 26, 2026
Security Audits
Gen Agent Trust HubPassSocketWarnSnykPass
Installed on
codex72
cursor70
gemini-cli69
opencode69
github-copilot68
amp68
${SKILL_ROOT}/references/metrics.md |
| Crons | Celery Beat, APScheduler, or cron patterns | ${SKILL_ROOT}/references/crons.md |
| AI Monitoring | OpenAI/Anthropic/LangChain/etc. detected | ${SKILL_ROOT}/references/ai-monitoring.md |
| Starlette | Before app = Starlette(...) | Same auto-integration as FastAPI |
| AIOHTTP | Module level, before web.Application() |
| Tornado | Module level, before app setup | No integration class needed |
| Quart | Before app = Quart(__name__) |
| Falcon | Module level, before app = falcon.App() |
| Sanic | Inside @app.listener("before_server_start") | Sanic's lifecycle requires async init |
| Celery | @signals.celeryd_init.connect in worker AND in calling process | Dual-process init required |
| RQ | mysettings.py loaded by worker via rq worker -c mysettings |
| ARQ | Both worker module and enqueuing process |
WSGIIntegration / ASGIIntegration |
| Business KPIs / SLO tracking |
| Crons | ${SKILL_ROOT}/references/crons.md | Scheduler / cron patterns detected |
| AI Monitoring | ${SKILL_ROOT}/references/ai-monitoring.md | AI library detected |
SENTRY_ENVIRONMENTrelease | str | None | e.g., "myapp@1.0.0"; env: SENTRY_RELEASE |
send_default_pii | bool | False | Include IP, headers, cookies, auth user |
traces_sample_rate | float | None | Transaction sample rate; None disables tracing |
traces_sampler | Callable | None | Custom per-transaction sampling (overrides rate) |
profile_session_sample_rate | float | None | Continuous profiling session rate |
profile_lifecycle | str | "manual" | "trace" = auto-start profiler with spans |
profiles_sample_rate | float | None | Transaction-based profiling rate |
enable_logs | bool | False | Send logs to Sentry (SDK ≥ 2.35.0) |
sample_rate | float | 1.0 | Error event sample rate |
attach_stacktrace | bool | False | Stack traces on capture_message() |
max_breadcrumbs | int | 100 | Max breadcrumbs per event |
debug | bool | False | Verbose SDK debug output |
before_send | Callable | None | Hook to mutate/drop error events |
before_send_transaction | Callable | None | Hook to mutate/drop transaction events |
ignore_errors | list | [] | Exception types or regex patterns to suppress |
auto_enabling_integrations | bool | True | Set False to disable all auto-detection |
debug |
StarletteIntegrationFastApiIntegration| Celery task errors not captured | Must call sentry_sdk.init() in the worker process via celeryd_init signal |
| Sanic init not working | Init must be inside @app.listener("before_server_start"), not module level |
| uWSGI not capturing | Add --enable-threads --py-call-uwsgi-fork-hooks to uWSGI command |
| No traces appearing | Verify traces_sample_rate is set (not None); check that the integration is auto-enabled |
| Profiling not starting | Requires traces_sample_rate > 0 + either profile_session_sample_rate or profiles_sample_rate |
enable_logs not working | Requires SDK ≥ 2.35.0; for direct structured logs use sentry_sdk.logger; for stdlib bridging use LoggingIntegration(sentry_logs_level=...) |
| Too many transactions | Lower traces_sample_rate or use traces_sampler to drop health checks |
| Cross-request data leaking | Don't use get_global_scope() for per-request data — use get_isolation_scope() |
| RQ worker not reporting | Pass --sentry-dsn="" to disable RQ's own Sentry shortcut; init via settings file instead |