Claude
Skills
Sign in
Back

sentry-python-sdk

Included with Lifetime
$97 forever

Full Sentry SDK setup for Python. Use when asked to "add Sentry to Python", "install sentry-sdk", "setup Sentry in Python", or configure error monitoring, tracing, profiling, logging, metrics, crons, or AI monitoring for Python applications. Supports Django, Flask, FastAPI, Celery, Starlette, AIOHTTP, Tornado, and more.

sdk-setup

What this skill does


> [All Skills](../../SKILL_TREE.md) > [SDK Setup](../sentry-sdk-setup/SKILL.md) > Python SDK

# Sentry Python SDK

Opinionated wizard that scans your Python project and guides you through complete Sentry setup.

## 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`, `sentry_sdk`, or Sentry + any Python framework
- 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/](https://docs.sentry.io/platforms/python/) before implementing.

---

## Phase 1: Detect

Run these commands to understand the project before making recommendations:

```bash
# 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|pyramid" \
  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

# OpenTelemetry tracing — check for SDK + instrumentations
grep -rE "opentelemetry-sdk|opentelemetry-instrumentation|opentelemetry-distro" \
  requirements.txt pyproject.toml 2>/dev/null
grep -rn "TracerProvider\|trace\.get_tracer\|start_as_current_span" \
  --include="*.py" 2>/dev/null | head -5

# 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.)
- OpenTelemetry tracing? (Use OTLP path instead of native tracing.)
- Companion frontend? (Triggers Phase 4 cross-link.)

---

## Phase 2: Recommend

Based on what you found, present a concrete proposal. Don't ask open-ended questions — lead with a recommendation:

**Route from OTel detection:**
- **OTel tracing detected** (`opentelemetry-sdk` / `opentelemetry-distro` in requirements, or `TracerProvider` in source) → use OTLP path: `OTLPIntegration()`; do **not** set `traces_sample_rate`; Sentry links errors to OTel traces automatically

**Always recommended (core coverage):**
- ✅ **Error Monitoring** — captures unhandled exceptions, supports `ExceptionGroup` (Python 3.11+)
- ✅ **Logging** — Python `logging` stdlib auto-captured; enhanced if Loguru detected

**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; **not available with OTLP path**
- ⚡ **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 | `${SKILL_ROOT}/references/error-monitoring.md` |
| OTLP Integration | OTel tracing detected — **replaces** native Tracing | `${SKILL_ROOT}/references/tracing.md` |
| Tracing | Django/Flask/FastAPI/AIOHTTP/etc. detected; **skip if OTel tracing detected** | `${SKILL_ROOT}/references/tracing.md` |
| Profiling | Production + performance-sensitive workload; **skip if OTel tracing detected** (requires `traces_sample_rate`, incompatible with OTLP) | `${SKILL_ROOT}/references/profiling.md` |
| Logging | Always (stdlib); enhanced for Loguru | `${SKILL_ROOT}/references/logging.md` |
| Metrics | Business events or SLO tracking needed | `${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` |

**OTel tracing detected:** *"I see OpenTelemetry tracing in the project. I recommend Sentry's OTLP integration for tracing (via your existing OTel setup) + Error Monitoring + Sentry Logging [+ Metrics/Crons/AI Monitoring if applicable]. Shall I proceed?"*

**No OTel:** *"I recommend Error Monitoring + Tracing [+ Logging if applicable]. Want Profiling, Crons, or AI Monitoring too?"*

---

## Phase 3: Guide

### Install

```bash
# 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-sdk` works for all frameworks. Extras install complementary packages.

### 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. "[email protected]"
    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,
)
```

### Where to Initialize Per Framework

| 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 |
| **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()` | |
| **Pyramid** | Module level, before `config = Configurator()` | WSGI framework |
| **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 | |

**Django example** (`settings.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,
)

# rest of Django settings...
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",
    enab

Related in sdk-setup