ASGI

Learn about the ASGI integration and how it adds support for ASGI applications.

The ASGI middleware can be used to instrument any ASGI-compatible web framework to attach request data for your events.

Copied
pip install "sentry-sdk"

In addition to capturing errors, you can monitor interactions between multiple services or applications by enabling tracing. You can also collect and analyze performance profiles from real users with profiling.

Select which Sentry features you'd like to install in addition to Error Monitoring to get the corresponding installation and configuration instructions below.

Copied
import sentry_sdk
from sentry_sdk.integrations.asgi import SentryAsgiMiddleware

from my_asgi_app import app

sentry_sdk.init(
    dsn="https://examplePublicKey@o0.ingest.sentry.io/0",
    # Add data like request headers and IP for users, if applicable;
    # see https://docs.sentry.io/platforms/python/data-management/data-collected/ for more info
    send_default_pii=True,
    #  performance
    # Set traces_sample_rate to 1.0 to capture 100%
    # of transactions for tracing.
    traces_sample_rate=1.0,
    #  performance
    #  profiling
    # To collect profiles for all profile sessions,
    # set `profile_session_sample_rate` to 1.0.
    profile_session_sample_rate=1.0,
    # Profiles will be automatically collected while
    # there is an active span.
    profile_lifecycle="trace",
    #  profiling
)

app = SentryAsgiMiddleware(app)

The middleware supports both ASGI 2 and ASGI 3.

Trigger an error in your code and see it show up in sentry.io.

Copied
sentry_sdk.init(...) # same as above

def app(scope):
    async def get_body():
        return f"The number is: {1/0}" # raises an error!

    async def asgi(receive, send):
        await send(
            {
                "type": "http.response.start",
                "status": 200,
                "headers": [[b"content-type", b"text/plain"]],
            }
        )
        await send({"type": "http.response.body", "body": await get_body()})

    return asgi

app = SentryAsgiMiddleware(app)

Run your ASGI app with unicorn:

Copied
uvicorn main:app --port 8000

Point your browser to http://localhost:8000 to trigger the error which is then sent to Sentry.

Additionally, a transaction will show up in the "Performance" section on sentry.io.

  • Request data is attached to all events: HTTP method, URL, headers. 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.

  • Each request has a separate scope. Changes to the scope within a view, for example setting a tag, will only apply to events sent as part of the request being handled.

  • The ASGI middleware does not behave like a regular integration. It is not initialized through an extra parameter to init and is not attached to a client. When capturing or supplementing events, it just uses the currently active scopes.

A set of predefined span attributes will be attached to ASGI transactions by default. These can also be used for sampling since they will also be accessible via the sampling_context dictionary in the traces_sampler.

Span AttributeDescription
network.protocol.nametype on ASGI scope
url.schemescheme on ASGI scope
url.pathpath on ASGI scope
url.queryquery on ASGI scope
network.protocol.versionhttp_version on ASGI scope
http.request.methodmethod on ASGI scope
server.address, server.portserver on ASGI scope
client.address, client.portclient on ASGI scope
url.fullfull URL, reconstructed from individual ASGI scope parts
http.request.header.{header}headers on ASGI scope

These attributes will also be sent to Sentry. If you don't want that, you can filter them out using a custom before_send function.

  • Python: 3.7+
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").