Starlette for Python
Learn how to set up Sentry in your Starlette app, capture your first events and traces, and view them in Sentry.
In SDK 3.x, and in stream mode in SDK 2.x, this page's references to "transaction" apply to service spans instead. See Streamed Spans for more information.
You need:
- A Sentry account and project
- Your application up and running
- Starlette:
0.16+(SDK <3.0)0.20+(SDK 3.0+)
- Python:
3.7+
Run the command for your preferred package manager to add the Sentry SDK to your application:
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.
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.
Configuration should happen as early as possible in your application's lifecycle.
If you have the starlette package in your dependencies, the Sentry Starlette integration will be enabled automatically when you initialize the Sentry SDK.
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_rateandprofile_lifecycle
Don't need a feature? Remove its options from the snippet.
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",
)
To further customize your setup, review the Options section below.
Sentry automatically captures errors and reports issues for you. You can also expect the following for your Starlette project:
- By default, all exceptions leading to an Internal Server Error are reported. The HTTP status codes to report on are configurable via the
failed_request_status_codesoption. - Request data will be attached to all events: HTTP method, URL, headers, form data, JSON payloads. Sentry excludes raw bodies and multipart file uploads.
- Personally identifiable information (such as user IDs, usernames, cookies, and IP addresses) is also attached, with sensitive values like authorization headers scrubbed. Use the
data_collectionoption to configure which categories to collect. In SDK versions prior to3.0, Sentry excludes this information unless you usedata_collectionor setsend_default_piitoTrue.
To learn how to manually report issues, see Capturing Errors.
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 as Sentry logs, add the corresponding integration to your integrations. See the standard logging and Loguru integration guides.
See Set Up Logs for all available logging methods and formatting options.
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"})
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.
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")
Let's test your setup and confirm that data reaches your Sentry project.
Add this route to your Starlette app, then request /sentry-debug:
from starlette.applications import Starlette
from starlette.routing import Route
async def trigger_error(request):
1 / 0
app = Starlette(routes=[Route("/sentry-debug", trigger_error)])
from starlette.applications import Starlette
from starlette.routing import Route
async def trigger_error(request):
1 / 0
app = Starlette(routes=[Route("/sentry-debug", trigger_error)])
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).
In SDK 3.x, and in stream mode in SDK 2.x, these options still work as described, but apply to service spans instead of transactions.
Add StarletteIntegration to your sentry_sdk.init() call to set options for StarletteIntegration to change its behavior.
from sentry_sdk.integrations.starlette import StarletteIntegration
sentry_sdk.init(
# ...
integrations=[
StarletteIntegration(
failed_request_status_codes={403, *range(500, 599)},
middleware_spans=False,
http_methods_to_capture=("GET",),
)
],
)
from sentry_sdk.integrations.starlette import StarletteIntegration
sentry_sdk.init(
# ...
integrations=[
StarletteIntegration(
failed_request_status_codes={403, *range(500, 599)},
middleware_spans=False,
http_methods_to_capture=("GET",),
)
],
)
You can pass the following keyword arguments to StarletteIntegration():
transaction_style
| Type | string |
|---|---|
| Default | "url" |
Only available in SDK versions prior to 3.0. In SDK 3.x, service spans are always named after the route pattern, for example /catalog/product/{product_id}.
How to name transactions that show up in Sentry tracing. The default is "url".
In the code example, the transaction name will be:
"/catalog/product/{product_id}"if you settransaction_style="url"."product_detail"if you settransaction_style="endpoint"
async def product_detail(request):
return JSONResponse({...})
app = Starlette(routes=[
Route('/catalog/product/{product_id}', product_detail),
])
async def product_detail(request):
return JSONResponse({...})
app = Starlette(routes=[
Route('/catalog/product/{product_id}', product_detail),
])
failed_request_status_codes
| Type | set[int] |
|---|---|
| Default | {*range(500, 600)} |
A set of integers that will determine which status codes should be reported to Sentry.
The failed_request_status_codes option determines whether HTTPException exceptions should be reported to Sentry. Unhandled exceptions that don't have a status_code attribute will always be reported to Sentry.
Examples of valid failed_request_status_codes:
{500}will only send events on HTTP 500.{400, *range(500, 600)}will send events on HTTP 400 as well as the 5xx range.{500, 503}will send events on HTTP 500 and 503.set()(the empty set) will not send events for any HTTP status code.
The default is {*range(500, 600)}, meaning that all 5xx status codes are reported to Sentry.
middleware_spans
| Type | bool |
|---|---|
| Default | False |
Create spans and track performance of all middleware layers in your project. Set to True to enable. The default is False.
http_methods_to_capture
| Available since | 2.15.0 |
|---|---|
| Type | Tuple[str, ...] |
| Default | ("CONNECT", "DELETE", "GET", "PATCH", "POST", "PUT", "TRACE",) |
A tuple containing all the HTTP methods (as uppercase strings) that should create a transaction in Sentry. The default is ("CONNECT", "DELETE", "GET", "PATCH", "POST", "PUT", "TRACE",).
Note that OPTIONS and HEAD are excluded by default.
At this point, you should have integrated Sentry into your Starlette 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
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").