Sentry Error Tracking in Python — Core Concepts

Production applications fail in ways that are hard to reproduce. A user hits an edge case, a third-party API returns unexpected data, or a race condition surfaces under load. Sentry captures these failures with enough context to diagnose them without reproducing them.

Sentry is an error tracking platform that integrates with Python applications to automatically capture exceptions, group them into issues, and provide the context needed to fix them.

Setup

Install and initialize the SDK:

import sentry_sdk

sentry_sdk.init(
    dsn="https://examplePublicKey@o0.ingest.sentry.io/0",
    traces_sample_rate=0.1,  # 10% of transactions for performance monitoring
    environment="production",
    release="order-service@2.4.1",
)

For frameworks, Sentry provides specific integrations:

# Django — auto-detected
sentry_sdk.init(dsn="...", integrations=[DjangoIntegration()])

# Flask
from sentry_sdk.integrations.flask import FlaskIntegration
sentry_sdk.init(dsn="...", integrations=[FlaskIntegration()])

# FastAPI
from sentry_sdk.integrations.fastapi import FastApiIntegration
sentry_sdk.init(dsn="...", integrations=[FastApiIntegration()])

Once initialized, unhandled exceptions are captured automatically. No try/except wrapping needed.

How error grouping works

When Sentry receives an error, it creates a fingerprint based on the exception type and stack trace. Errors with the same fingerprint are grouped into a single issue. This means 10,000 occurrences of the same KeyError at the same location show as one issue with a count of 10,000.

You can customize grouping when the default is too broad or too narrow:

# Group all payment timeout errors together regardless of stack trace
sentry_sdk.set_tag("fingerprint", ["payment-timeout"])

Breadcrumbs are a timeline of events leading up to an error. Sentry automatically captures:

  • HTTP requests made by your app
  • Database queries
  • Log messages
  • User navigation (in web apps)

When you open an error in Sentry, the breadcrumb trail shows what happened in the 60 seconds before the crash, like rewinding a security camera.

Add custom breadcrumbs for application-specific events:

sentry_sdk.add_breadcrumb(
    category="payment",
    message=f"Processing payment for order {order_id}",
    level="info",
    data={"amount": 42.50, "provider": "stripe"}
)

Context and tags

Enrich errors with context that helps diagnosis:

# Tags are indexed and searchable
sentry_sdk.set_tag("payment_provider", "stripe")
sentry_sdk.set_tag("plan", "premium")

# User context
sentry_sdk.set_user({"id": 42, "email": "alice@example.com"})

# Extra context (not indexed, but visible on the error)
sentry_sdk.set_context("order", {
    "id": 789,
    "items": 3,
    "total": 99.50
})

Tags let you filter the Sentry dashboard: “Show me all errors from premium users” or “Show me errors related to Stripe.”

Release tracking

Setting the release parameter connects errors to specific code versions:

sentry_sdk.init(release="order-service@2.4.1")

This enables:

  • Regression detection: Sentry alerts you if an error that was resolved reappears in a new release.
  • Release health: See error rates and crash-free session percentages per release.
  • Commit integration: Link errors to the specific commits that introduced them (with GitHub/GitLab integration).

Performance monitoring

Sentry also tracks transaction performance:

with sentry_sdk.start_transaction(name="process_order", op="task"):
    validate_order()
    charge_payment()
    send_confirmation()

This creates a waterfall view showing how long each operation took. Combined with error tracking, you see both “what broke” and “what was slow.”

Common misconception

“Sentry is just for catching crashes.” Modern Sentry includes performance monitoring, release health tracking, session replay, and profiling. It has evolved from a simple error logger into a comprehensive application monitoring platform. However, its core strength remains error tracking — that is where most teams get the fastest return on investment.

When Sentry complements other tools

Sentry handles errors; Prometheus handles metrics; OpenTelemetry handles traces. They serve different purposes and work best together. Sentry tells you “this specific error happened to user 42 at this line of code.” Prometheus tells you “error rate increased to 5%.” OpenTelemetry tells you “this request took 3 seconds and the database was the bottleneck.”

One thing to remember: Sentry captures production errors with full context — stack traces, breadcrumbs, user info, and release data — so you can diagnose and fix bugs without needing to reproduce them.

pythonsentrymonitoring

See Also

  • Python Adaptive Learning Systems How Python builds learning apps that adjust to each student like a personal tutor who knows exactly what you need next.
  • Python Airflow Learn Airflow as a timetable manager that makes sure data tasks run in the right order every day.
  • Python Altair Learn Altair through the idea of drawing charts by describing rules, not by hand-placing every visual element.
  • Python Automated Grading How Python grades homework and exams automatically, from simple answer keys to understanding written essays.
  • Python Batch Vs Stream Processing Batch processing is like doing laundry once a week; stream processing is like a self-cleaning shirt that cleans itself constantly.