Skip to content
115 changes: 58 additions & 57 deletions docs/platforms/python/index.mdx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
title: Python
description: Learn how to set up Sentry in your Python app, capture your first errors and traces, and view them in Sentry.
description: Learn how to set up Sentry in your Python app, capture your first events and traces, and view them in Sentry.
caseStyle: snake_case
supportLevel: production
sdk: sentry.python
Expand All @@ -26,13 +26,12 @@ This guide focuses on plain Python. If you're working with Django, FastAPI, Star

<PlatformContent includePath="getting-started-install" />

## Configure
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`.

Choose the features you want to configure, and this guide will show you how:
## Configure

<OnboardingOptionButtons
options={["error-monitoring", "performance", "profiling", "logs", "metrics"]}
/>
**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](#send-logs) and [#4](#send-application-metrics-).
This guide also enables **Tracing** and **Profiling**.

<Include name="quick-start-features-expandable" />

Expand All @@ -42,61 +41,53 @@ Configuration should happen as **early as possible** in your application's lifec

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 <PlatformLink to="/configuration/options/#data_collection">`data_collection`</PlatformLink>
- Tracing: via <PlatformLink to="/configuration/options/#traces_sample_rate">`traces_sample_rate`</PlatformLink>
- Profiling: via <PlatformLink to="/configuration/options/#profile_session_sample_rate">`profile_session_sample_rate`</PlatformLink> and <PlatformLink to="/configuration/options/#profile_lifecycle">`profile_lifecycle`</PlatformLink>

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

```python
import sentry_sdk
# ___PRODUCT_OPTION_START___ metrics
from sentry_sdk import metrics
# ___PRODUCT_OPTION_END___ metrics

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,
},
# ___PRODUCT_OPTION_START___ performance

# Set traces_sample_rate to 1.0 to capture 100%
# of transactions for tracing.
# see https://docs.sentry.io/platforms/python/configuration/options/#traces_sample_rate for more info
# 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,
# ___PRODUCT_OPTION_END___ performance
# ___PRODUCT_OPTION_START___ profiling

# Enables continuous profiling.
# To collect profiles for all profile sessions,
# set `profile_session_sample_rate` to 1.0.
# see https://docs.sentry.io/platforms/python/configuration/options/#profile_session_sample_rate for more info
# Enables Profiling.
# Set to 1.0 to profile 100% of sessions.
profile_session_sample_rate=1.0,

# Profiles will be automatically collected while
# there is an active span.
# see https://docs.sentry.io/platforms/python/configuration/options/#profile_lifecycle for more info
# Profiles are collected while a transaction is active.
profile_lifecycle="trace",
# ___PRODUCT_OPTION_END___ profiling
)
```

In async programs, we recommend to initialize the Sentry SDK inside an `async` function to ensure async code is instrumented properly. If possible, call `sentry_sdk.init()` at the beginning of the first `async` function you call:
In async programs, add the <PlatformLink to="/integrations/asyncio/">`AsyncioIntegration`</PlatformLink> 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:

```python
import asyncio
import sentry_sdk
# ___PRODUCT_OPTION_START___ metrics
from sentry_sdk import metrics
# ___PRODUCT_OPTION_END___ metrics

from sentry_sdk.integrations.asyncio import AsyncioIntegration

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

asyncio.run(main())
```

<OnboardingOption optionId="performance">
### Instrumenting Your App

The Sentry SDK automatically enables integrations for <PlatformLink to="/tracing/instrumentation/automatic-instrumentation/">many popular libraries</PlatformLink>, so operations like HTTP requests or database queries made with supported libraries will be captured as spans automatically.
Expand All @@ -113,41 +104,55 @@ def some_function():
...
```

</OnboardingOption>
## Send Logs

## Verify Your Setup
Use `sentry_sdk.logger` to send structured logs at different levels. You can include searchable attributes with each message.

Let's test your setup and confirm that data reaches your Sentry project.
To capture records from Python's standard-library `logging` module or Loguru, configure `capture_sentry_logs=True` on the corresponding integration. See the <PlatformLink to="/integrations/logging/">standard logging</PlatformLink> and <PlatformLink to="/integrations/loguru/">Loguru</PlatformLink> integration guides.

<Include name="python-quick-start-shell-warning.mdx" />
See <PlatformLink to="/logs/">Set Up Logs</PlatformLink> for all available logging methods and formatting options.

### Issues
```python
import sentry_sdk

To verify that Sentry captures errors and creates issues in your Sentry project, add this intentional error to your application:
sentry_sdk.logger.info("Order processed {order_id}", order_id="order-123")
sentry_sdk.logger.warning("Rate limit reached", attributes={"endpoint": "/api/orders"})
```

```py
## Send Application Metrics <FeatureBadge type="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 <PlatformLink to="/metrics/">Set Up Metrics</PlatformLink> for all available metric types and configuration options.

```python
import sentry_sdk

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

<OnboardingOption optionId="performance">

<Include name="tracing/python-quick-start-verify-tracing-splitlayout.mdx" />
## Verify Your Setup

</OnboardingOption>
Let's test your setup and confirm that data reaches your Sentry project.

<OnboardingOption optionId="logs">
Run this code after `sentry_sdk.init()` to send a test error, along with a trace, a log, and a metric:

<Include name="logs/python-quick-start-verify-logs-splitlayout.mdx" />
```python
import sentry_sdk

</OnboardingOption>
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
```

<OnboardingOption optionId="metrics">
<Alert>

<Include name="metrics/python-quick-start-verify-metrics-splitlayout.mdx" />
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.

</OnboardingOption>
</Alert>

### View Captured Data in Sentry

Expand All @@ -157,15 +162,11 @@ Now, head over to your project on [Sentry.io](https://sentry.io) to view the col

## Next Steps

At this point, you should have integrated Sentry into your Python application and should already be sending data to your Sentry project.

Now's a good time to customize your setup and look into more advanced topics.
Our next recommended steps for you are:
At this point, you should have integrated Sentry into your Python application. Here's what to explore next:

- Explore [practical guides](/get-started/guides/) on what to monitor, log, track, and investigate after setup
- Continue to <PlatformLink to="/configuration/">customize your configuration</PlatformLink>
- Learn more about <PlatformLink to="/usage/">manually capturing errors or messages</PlatformLink>
- Dive straight into the API with our [API docs](https://getsentry.github.io/sentry-python/)
- <PlatformLink to="/agent-tracing/">Set up Agent Tracing</PlatformLink> to monitor your AI systems
- Learn how to <PlatformLink to="/usage/">manually capture errors</PlatformLink>

<Expandable permalink={false} title="Are you having problems setting up the SDK?">

Expand Down
Loading
Loading