✨ Include route in scope to allow middleware and other tools to extract its information by tiangolo · Pull Request #4603 · fastapi/fastapi · GitHub
Skip to content

✨ Include route in scope to allow middleware and other tools to extract its information - #4603

Merged
tiangolo merged 2 commits into
masterfrom
scope-include-route
Feb 21, 2022
Merged

tiangolo merged 2 commits into
masterfrom
scope-include-route

Conversation

@tiangolo

@tiangolo tiangolo commented Feb 21, 2022

Copy link
Copy Markdown
Member

This is useful, in particular, for external tools handling errors, logs, observability, etc. like Sentry.

There's a counterpart PR in Sentry: getsentry/sentry-python#1349


If you need this now, you can update Sentry's middleware like this:

from typing import TYPE_CHECKING, Any, Optional

from fastapi import FastAPI
from fastapi.routing import APIRoute
from sentry_sdk.integrations.asgi import SentryAsgiMiddleware

if TYPE_CHECKING:
    from sentry_sdk._types import Event, Hint

app = FastAPI()


class CustomSentryAsgiMiddleware(SentryAsgiMiddleware):
    def event_processor(
        self, event: "Event", hint: "Hint", asgi_scope: Any
    ) -> "Optional[Event]":
        result_event = super().event_processor(event, hint, asgi_scope)
        route: Optional[APIRoute] = asgi_scope.get("route")
        if route and result_event:
            result_event["transaction"] = route.path
        return result_event


app.add_middleware(CustomSentryAsgiMiddleware)

@codecov

codecov Bot commented Feb 21, 2022

Copy link
Copy Markdown

@github-actions

Copy link
Copy Markdown
Contributor

@github-actions

Copy link
Copy Markdown
Contributor

@tiangolo
tiangolo merged commit f5d7df3 into master Feb 21, 2022
@tiangolo
tiangolo deleted the scope-include-route branch February 21, 2022 15:51
JeanArhancet pushed a commit to JeanArhancet/fastapi that referenced this pull request Aug 20, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant