Starlette

The Starlette integration adds support for the Starlette Framework.

The Sentry SDK automatically enables support for Starlette if you have the starlette Python package installed in your project. There are no configuration options you need to add when initializing the Sentry SDK, as everything works out of the box.

Install

Install sentry-sdk from PyPI with the starlette extra:

Copied
pip install --upgrade 'sentry-sdk[starlette]'

Configure

To configure the SDK, initialize it with the integration before your app has been initialized:

Copied
from starlette.applications import Starlette

import sentry_sdk


sentry_sdk.init(
    dsn="https://examplePublicKey@o0.ingest.sentry.io/0",

    # Set traces_sample_rate to 1.0 to capture 100%
    # of transactions for performance monitoring.
    # We recommend adjusting this value in production,
    traces_sample_rate=1.0,
)

app = Starlette(routes=[...])

Verify

This snippet includes an intentional error, so you can test that everything is working as soon as you set it up:

Copied
from starlette.applications import Starlette
from starlette.routing import Route


async def trigger_error(request):
    division_by_zero = 1 / 0

app = Starlette(routes=[
    Route("/sentry-debug", trigger_error),
])

Visiting "/sentry-debug" will trigger an error that will be captured by Sentry.

Behavior

  • All exceptions leading to an Internal Server Error are reported.

  • Request data is attached to all events: HTTP method, URL, headers, form data, JSON payloads. Sentry excludes raw bodies and multipart file uploads. Sentry also excludes personally identifiable information (such as user ids, usernames, cookies, authorization headers, IP addresses) unless you set send_default_pii to True.

  • If a traces_sample_rate is set, then performance information is also reported, which you can see on the Performance page of sentry.io.

Options

If you want to change the default behavior of the Starlette integration, you need to instantiate the integration by hand and pass it to Sentry's init function.

You can pass the keyword argument transaction_style to StarletteIntegration().

With this option, you can influence how the transactions are named in Sentry. For example:

Copied
from sentry_sdk.integrations.starlette import StarletteIntegration

sentry_sdk.init(
    # ...
    integrations=[
        StarletteIntegration(transaction_style="endpoint"),
    ],
)

async def product_detail(request):
    return JSONResponse({...})

app = Starlette(routes=[
    Route('/catalog/product/{product_id}', product_detail),
])

In the above code, the transaction name will be:

  • "/catalog/product/{product_id}" if you set transaction_style="url".
  • "product_detail" if you set transaction_style="endpoint"

The default is "url".

Help improve this content
Our documentation is open source and available on GitHub. Your contributions are welcome, whether fixing a typo (drat!) to suggesting an update ("yeah, this would be better").