Skip to content
arminrad edited this page Mar 16, 2026 · 2 revisions

Error Monitoring (Sentry)

Real-time error tracking and alerting with Sentry


Overview

Comprehensive error monitoring:

  • Automatic error capture
  • Real-time alerts
  • Stack traces
  • User context
  • Release tracking
  • Performance monitoring

Provider: Sentry.io


Quick Start

Setup

SENTRY_DSN=https://xxx@xxx.ingest.sentry.io/xxx
SENTRY_ENVIRONMENT=production
SENTRY_TRACES_SAMPLE_RATE=0.1

Initialize

# src/main.py
import sentry_sdk

sentry_sdk.init(
    dsn=os.getenv("SENTRY_DSN"),
    environment=os.getenv("SENTRY_ENVIRONMENT", "production"),
    traces_sample_rate=float(os.getenv("SENTRY_TRACES_SAMPLE_RATE", "0.1")),
    profiles_sample_rate=0.1,
)

Automatic Capture

Exceptions

# Automatically captured
try:
    result = risky_operation()
except Exception as e:
    # Sentry captures this
    raise

FastAPI Integration

from sentry_sdk.integrations.fastapi import FastApiIntegration

sentry_sdk.init(
    dsn=dsn,
    integrations=[FastApiIntegration()],
)

Manual Capture

Capture Exception

from sentry_sdk import capture_exception

try:
    process_payment()
except PaymentError as e:
    capture_exception(e)
    return {"error": "Payment failed"}

Capture Message

from sentry_sdk import capture_message

capture_message("Unusual activity detected", level="warning")

Add Context

from sentry_sdk import set_user, set_tag, set_context

# User context
set_user({"id": user.id, "email": user.email})

# Tags for filtering
set_tag("payment_method", "stripe")
set_tag("plan", "pro")

# Additional context
set_context("payment", {
    "amount": 100,
    "currency": "usd"
})

Error Grouping

Sentry groups similar errors automatically:

# These will be grouped together
raise ValueError("Invalid amount: 100")
raise ValueError("Invalid amount: 200")
# → Grouped as "ValueError: Invalid amount"

Custom Fingerprints

from sentry_sdk import configure_scope

with configure_scope() as scope:
    scope.fingerprint = ["custom-group", error_type]

Filtering Errors

Ignore Specific Errors

sentry_sdk.init(
    dsn=dsn,
    ignore_errors=[
        KeyboardInterrupt,
        "ConnectionError",
    ],
    before_send=filter_errors,
)

def filter_errors(event, hint):
    # Don't send 404 errors
    if event.get('request', {}).get('url', '').endswith('/favicon.ico'):
        return None
    return event

Performance Monitoring

Transaction Tracking

from sentry_sdk import start_transaction

with start_transaction(op="function", name="process_payment"):
    result = process_payment()

Custom Spans

with start_transaction(op="task", name="sync_models"):
    with sentry_sdk.start_span(op="db", description="fetch models"):
        models = fetch_models()

    with sentry_sdk.start_span(op="http", description="update pricing"):
        update_pricing(models)

Releases

Track Deployments

# Create release
sentry-cli releases new v2.0.3

# Associate commits
sentry-cli releases set-commits v2.0.3 --auto

# Deploy
sentry-cli releases deploys v2.0.3 new -e production

# Finalize
sentry-cli releases finalize v2.0.3

In Code

sentry_sdk.init(
    dsn=dsn,
    release="v2.0.3",
)

Alerts

Configure in Sentry

  1. Go to AlertsCreate Alert
  2. Set conditions:
    • When: Error count > 10 in 1 minute
    • Filter: environment:production
  3. Actions:
    • Send email
    • Slack notification
    • PagerDuty

Alert Types

  • Error frequency: Too many errors
  • New issues: First time seeing error
  • Regression: Previously resolved error returns
  • Performance: Slow transactions

Best Practices

  1. Add context: User ID, request ID, etc.
  2. Filter noise: Ignore expected errors
  3. Set sample rate: Don't send 100% of events
  4. Use releases: Track which version has issues
  5. Assign ownership: Team/person per error type
  6. Resolve issues: Mark as resolved when fixed
  7. Review regularly: Weekly error review

Dashboard

Key Metrics

  • Error rate: Errors per minute
  • Affected users: Unique users hit by errors
  • Crash-free sessions: % sessions without errors
  • Release health: Errors per release

Useful Views

  • Issues: All error groups
  • Performance: Transaction performance
  • Releases: Deployment tracking
  • User Feedback: User-reported issues

Integration with Logging

import logging
from sentry_sdk.integrations.logging import LoggingIntegration

sentry_logging = LoggingIntegration(
    level=logging.INFO,
    event_level=logging.ERROR
)

sentry_sdk.init(
    dsn=dsn,
    integrations=[sentry_logging],
)

Troubleshooting

Events not appearing

Cause: Wrong DSN or environment

Solution: Check SENTRY_DSN and test with:

sentry_sdk.capture_message("Test message")

Too many events

Cause: Sample rate too high

Solution: Reduce traces_sample_rate

Missing context

Cause: Context not set before error

Solution: Set context early in request:

set_user({"id": user_id})

Related Documentation


Last Updated: December 2024 Status: Production Ready


Related

Clone this wiki locally