@@ -227,7 +227,7 @@ def instrument_app(
227
227
app .add_middleware (
228
228
OpenTelemetryMiddleware ,
229
229
excluded_urls = excluded_urls ,
230
- default_span_details = _get_route_details ,
230
+ default_span_details = _get_default_span_details ,
231
231
server_request_hook = server_request_hook ,
232
232
client_request_hook = client_request_hook ,
233
233
client_response_hook = client_response_hook ,
@@ -300,7 +300,7 @@ def __init__(self, *args, **kwargs):
300
300
self .add_middleware (
301
301
OpenTelemetryMiddleware ,
302
302
excluded_urls = _InstrumentedFastAPI ._excluded_urls ,
303
- default_span_details = _get_route_details ,
303
+ default_span_details = _get_default_span_details ,
304
304
server_request_hook = _InstrumentedFastAPI ._server_request_hook ,
305
305
client_request_hook = _InstrumentedFastAPI ._client_request_hook ,
306
306
client_response_hook = _InstrumentedFastAPI ._client_response_hook ,
@@ -316,26 +316,49 @@ def __del__(self):
316
316
317
317
318
318
def _get_route_details (scope ):
319
- """Callback to retrieve the fastapi route being served.
320
-
319
+ """
320
+ Function to retrieve Starlette route from scope.
321
+
321
322
TODO: there is currently no way to retrieve http.route from
322
323
a starlette application from scope.
323
-
324
324
See: https://github.com/encode/starlette/pull/804
325
+
326
+ Args:
327
+ scope: A Starlette scope
328
+ Returns:
329
+ A string containing the route or None
325
330
"""
326
331
app = scope ["app" ]
327
332
route = None
333
+
328
334
for starlette_route in app .routes :
329
335
match , _ = starlette_route .matches (scope )
330
336
if match == Match .FULL :
331
337
route = starlette_route .path
332
338
break
333
339
if match == Match .PARTIAL :
334
340
route = starlette_route .path
335
- # method only exists for http, if websocket
336
- # leave it blank.
337
- span_name = route or scope .get ("method" , "" )
341
+ return route
342
+
343
+
344
+ def _get_default_span_details (scope ):
345
+ """
346
+ Callback to retrieve span name and attributes from scope.
347
+
348
+ Args:
349
+ scope: A Starlette scope
350
+ Returns:
351
+ A tuple of span name and attributes
352
+ """
353
+ route = _get_route_details (scope )
354
+ method = scope .get ("method" , "" )
338
355
attributes = {}
339
356
if route :
340
357
attributes [SpanAttributes .HTTP_ROUTE ] = route
358
+ if method and route : # http
359
+ span_name = f"{ method } { route } "
360
+ elif route : # websocket
361
+ span_name = route
362
+ else : # fallback
363
+ span_name = method
341
364
return span_name , attributes
0 commit comments