Sentry ASGI integration: initialization during "startup" event is not applied to "Hub.main"

Hi all,

I’ve been trying to integrate Sentry into a Python app that is built with FastAPI and thus runs on Starlette/Uvicorn. The initialisation code looks something like this:

def initialize_sentry_sdk():
    """Initialize Sentry according to current configuration."""
    kwargs = {
        'dsn': settings.sentry_dsn,
        'transport': HttpTransportWithTimeout,
        'environment': settings.environment,
        # 'debug': True,
    if settings.release_id:
        kwargs['release'] = settings.release_id
app.add_event_handler('startup', initialize_sentry_sdk)

And I was quite surprised to see that it was not working. After a quite long debugging session I figured out that “hub.client” was not configured in the request handlers. And that happened because the “startup” event was handled inside a Sentry scope, and thus “sentry_sdk.init” was not applied to the “Hub.main” instance which would be inherited for each newly created request scope.

Is this intended?

I can probably initialize Sentry during loading the module instead of server startup, or I could maybe make another middleware that would load Sentry settings right before starting the app, or I could copy the settings from “Hub.current” to “Hub.main” manually, but none of these methods feel right. Is there a better way?

Hi, sorry for the late reply. I guess I am confused why you would not want to initialize the SDK during module import? You can set the release at a later point by doing something like Hub.current.client.options['release'] = ... if you really need to.

It is more in the line of why you wouldn’t configure logging outputs (handlers) during a module import, because it is a side effect and a module cannot decide what is it being imported for by the actual program. E.g. I may want to import the same module from a Jupyter session, and I don’t want sentry reports for exceptions that I generate interactively.