diff --git a/sentry_sdk/integrations/aiohttp.py b/sentry_sdk/integrations/aiohttp.py index 3819256773..42f91739b6 100644 --- a/sentry_sdk/integrations/aiohttp.py +++ b/sentry_sdk/integrations/aiohttp.py @@ -233,6 +233,7 @@ async def sentry_app_handle( }, parent_span=None, ) + scope.get_current_scope()._server_segment_span = span_ctx else: transaction = continue_trace( headers, @@ -323,14 +324,19 @@ async def sentry_urldispatcher_resolve( if integration is None: return rv + route_info = rv.get_info() + pattern = route_info.get("path") or route_info.get("formatter") + + server_span = sentry_sdk.get_current_scope()._server_segment_span + if server_span is not None and pattern is not None: + server_span.set_attribute(SPANDATA.HTTP_ROUTE, pattern) + name = None try: if integration.transaction_style == "handler_name": name = transaction_from_function(rv.handler) elif integration.transaction_style == "method_and_path_pattern": - route_info = rv.get_info() - pattern = route_info.get("path") or route_info.get("formatter") name = "{} {}".format(request.method, pattern) except Exception: pass diff --git a/tests/integrations/aiohttp/test_aiohttp.py b/tests/integrations/aiohttp/test_aiohttp.py index 3eefdc9444..918148b062 100644 --- a/tests/integrations/aiohttp/test_aiohttp.py +++ b/tests/integrations/aiohttp/test_aiohttp.py @@ -1882,6 +1882,42 @@ async def hello(request): assert server_segment["attributes"]["sentry.segment.name.source"] == expected_source +@pytest.mark.asyncio +@pytest.mark.parametrize( + "url,expected_route", + [ + ("/message", "/{var}"), + ], +) +async def test_http_route( + sentry_init, + aiohttp_client, + capture_items, + url, + expected_route, +): + sentry_init( + integrations=[AioHttpIntegration()], + traces_sample_rate=1.0, + trace_lifecycle="stream", + ) + + async def hello(request): + return web.Response(text="hello") + + app = web.Application() + app.router.add_get(r"/{var}", hello) + + items = capture_items("span") + + client = await aiohttp_client(app) + await client.get(url) + + sentry_sdk.flush() + (segment,) = (item.payload for item in items if item.payload.get("is_segment")) + assert segment["attributes"][SPANDATA.HTTP_ROUTE] == expected_route + + @pytest.mark.asyncio async def test_server_error_span_streaming(sentry_init, aiohttp_client, capture_items): sentry_init(