GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Docs
  • Get Started
  • SDKs
  • Product
  • AI
  • API
  • Go to Sentry

This view

  • Original page
  • New address

GeezerVison is showing docs.sentry.io — Python | Sentry for Python

  • Home
  • Platforms
  • Python

Sentry for Python

Learn how to set up Sentry in your Python app, capture your first events and traces, and view them in Sentry.

Set up with Sentry CLI
curl https://cli.sentry.dev/install -fsS | bash
Learn more about the Sentry CLI

Set up with Sentry CLI

Set up the Sentry Python SDK with the Sentry CLI. Install the CLI with one of these commands, then follow the Sentry CLI docs to finish setup.

cURL

curl https://cli.sentry.dev/install -fsS | bash

PowerShell

irm https://cli.sentry.dev/install.ps1 | iex

Homebrew

brew install getsentry/tools/sentry

npx

npx sentry@latest

Learn more about the Sentry CLI

Using a framework?

This guide focuses on plain Python. If you're working with Django, FastAPI, Starlette, or any other web framework, choose the respective guide from the list of supported frameworks.

Prerequisites

You need:

  • A Sentry account and project
  • Your application up and running
  • Python 3.6 or above

Install

Run the command for your preferred package manager to add the Sentry SDK to your application:

Copied
pip install "sentry-sdk"
pip install "sentry-sdk"
uv add "sentry-sdk"
poetry add "sentry-sdk"

This guide requires sentry-sdk version 2.70.0 or later. If you already have the SDK installed, upgrade it with pip install --upgrade sentry-sdk.

Configure

Error Monitoring starts working as soon as you call sentry_sdk.init(). Logs and Application Metrics need no extra configuration when using sentry_sdk.logger and sentry_sdk.metrics, and you'll learn how to send them in steps #3 and #4. This guide also enables Tracing and Profiling.

Want to learn more about these features?
  • Issues (always enabled): Sentry's core error monitoring product that automatically reports errors, uncaught exceptions, and crashes. If you have something that looks like an exception, Sentry can capture it.
  • Tracing: Track software performance while seeing the impact of errors across multiple systems. For example, distributed tracing allows you to follow a request from the frontend to the backend and back. On the server, this includes Agent Tracing: supported AI libraries are instrumented automatically, so you can see model calls, tool executions, and token usage.
  • Profiling: Gain deeper insight than traditional tracing without custom instrumentation, letting you discover slow-to-execute or resource-intensive functions in your app.
  • Logs: Centralize and analyze your application logs to correlate them with errors and performance issues. Search, filter, and visualize log data to understand what's happening in your applications.
  • Application Metrics (always enabled): Track and analyze custom application metrics, such as response times and database query durations, to understand trends and patterns in your application's performance and behavior over time.

Initialize the Sentry SDK

Configuration should happen as early as possible in your application's lifecycle.

Import and initialize the SDK in your app's entry point:

The snippet also turns on:

  • Collection of user data, such as the user's IP address: via data_collection
  • Tracing: via traces_sample_rate
  • Profiling: via profile_session_sample_rate and profile_lifecycle

Don't need a feature? Remove its options from the snippet.

Copied
import sentry_sdk
sentry_sdk.init(
    dsn="___PUBLIC_DSN___",

    # Check https://docs.sentry.io/platforms/python/data-management/data-collected/ to configure what data is collected
    data_collection={
        "user_info": True,
    },

    # Enables Tracing.
    # Set to 1.0 to capture 100% of spans for tracing.
    # We recommend reducing this value in production.
    traces_sample_rate=1.0,

    # Enables Profiling.
    # Set to 1.0 to profile 100% of sessions.
    profile_session_sample_rate=1.0,
    # Profiles are collected while a transaction is active.
    profile_lifecycle="trace",
)
import sentry_sdk
sentry_sdk.init(
    dsn="___PUBLIC_DSN___",

    # Check https://docs.sentry.io/platforms/python/data-management/data-collected/ to configure what data is collected
    data_collection={
        "user_info": True,
    },

    # Enables Tracing.
    # Set to 1.0 to capture 100% of spans for tracing.
    # We recommend reducing this value in production.
    traces_sample_rate=1.0,

    # Enables Profiling.
    # Set to 1.0 to profile 100% of sessions.
    profile_session_sample_rate=1.0,
    # Profiles are collected while a transaction is active.
    profile_lifecycle="trace",
)

In async programs, add the AsyncioIntegration to instrument your async code. This integration isn't enabled by default. Call sentry_sdk.init() at the beginning of the first async function you call:

Copied
import asyncio
import sentry_sdk
from sentry_sdk.integrations.asyncio import AsyncioIntegration

async def main():
    sentry_sdk.init(
        ...,  # same options as above
        integrations=[AsyncioIntegration()],
    )

asyncio.run(main())
import asyncio
import sentry_sdk
from sentry_sdk.integrations.asyncio import AsyncioIntegration

async def main():
    sentry_sdk.init(
        ...,  # same options as above
        integrations=[AsyncioIntegration()],
    )

asyncio.run(main())

Instrumenting Your App

The Sentry SDK automatically enables integrations for many popular libraries, so operations like HTTP requests or database queries made with supported libraries will be captured as spans automatically.

However, spans are only created within an existing transaction. If you're not using a supported framework that creates transactions automatically, you'll need to create them manually using sentry_sdk.start_transaction().

See Custom Instrumentation for more info.

Copied
import sentry_sdk

def some_function():
    with sentry_sdk.start_transaction(op="task", name="Test Transaction"):
        ...
import sentry_sdk

def some_function():
    with sentry_sdk.start_transaction(op="task", name="Test Transaction"):
        ...

Send Logs

Use sentry_sdk.logger to send structured logs at different levels. You can include searchable attributes with each message.

To capture records from Python's standard-library logging module or Loguru, configure capture_sentry_logs=True on the corresponding integration. See the standard logging and Loguru integration guides.

See Set Up Logs for all available logging methods and formatting options.

Copied
import sentry_sdk

sentry_sdk.logger.info("Order processed {order_id}", order_id="order-123")
sentry_sdk.logger.warning("Rate limit reached", attributes={"endpoint": "/api/orders"})
import sentry_sdk

sentry_sdk.logger.info("Order processed {order_id}", order_id="order-123")
sentry_sdk.logger.warning("Rate limit reached", attributes={"endpoint": "/api/orders"})

Send Application Metrics NEW

Use sentry_sdk.metrics to send counters, gauges, and distributions from your app. Metrics are enabled by default after you initialize the SDK.

See Set Up Metrics for all available metric types and configuration options.

Copied
import sentry_sdk

sentry_sdk.metrics.count("checkout.failed", 1)
sentry_sdk.metrics.gauge("active_connections", 42)
sentry_sdk.metrics.distribution("api_latency", 187, unit="millisecond")
import sentry_sdk

sentry_sdk.metrics.count("checkout.failed", 1)
sentry_sdk.metrics.gauge("active_connections", 42)
sentry_sdk.metrics.distribution("api_latency", 187, unit="millisecond")

Verify Your Setup

Let's test your setup and confirm that data reaches your Sentry project.

Run this code after sentry_sdk.init() to send a test error, along with a trace, a log, and a metric:

Copied
import sentry_sdk

with sentry_sdk.start_transaction(op="test", name="Verify Sentry setup"):
    sentry_sdk.logger.info("Sentry verification log")
    sentry_sdk.metrics.count("sentry.verification", 1)
    1 / 0
import sentry_sdk

with sentry_sdk.start_transaction(op="test", name="Verify Sentry setup"):
    sentry_sdk.logger.info("Sentry verification log")
    sentry_sdk.metrics.count("sentry.verification", 1)
    1 / 0

The SDK sends profiles after a transaction finishes, so a script that exits right away, like the one above, might not send a profile. Profiles appear for applications that keep running after their transactions complete.

View Captured Data in Sentry

Now, head over to your project on Sentry.io to view the collected data (it takes a couple of moments for the data to appear).

Need help locating captured data in your Sentry project?
  • Open the Issues page and select an error from the issues list to view the full details and context of this error. For more details, see the Issue Details documentation.
  • Open the Traces page and select a trace to reveal more information about each span, its duration, and any errors. For an interactive UI walkthrough, click here.
  • Open the Profiles page to see your slowest functions and an aggregate flame graph of your most frequent code paths. If tracing is enabled, select a transaction to see the flame graph for that part of your app. For more information, click here.
  • Open the Logs page and filter by service, environment, or search keywords to view log entries from your application. For an interactive UI walkthrough, click here.
  • Open the Application Metrics page to view and analyze your metrics. For more details, see this interactive walkthrough.

Next Steps

At this point, you should have integrated Sentry into your Python application. Here's what to explore next:

  • Explore practical guides on what to monitor, log, track, and investigate after setup
  • Set up Agent Tracing to monitor your AI systems
  • Learn how to manually capture errors
Are you having problems setting up the SDK?
  • Find various topics in Troubleshooting
  • Get support
Previous
Welcome to Sentry
Next
Capturing Errors
Was this helpful?
Help improve this content
Our documentation is open source and available on GitHub. Your contributions are welcome, whether fixing a typo (drat!) or suggesting an update ("yeah, this would be better").
How to contribute   |  Edit this page   |  Create a docs issue   |  Get support
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.