Skip to content

Commit c408058

Browse files
committed
Update Starlette instrumentation
1 parent 2d4abcd commit c408058

File tree

2 files changed

+30
-7
lines changed

2 files changed

+30
-7
lines changed

instrumentation/opentelemetry-instrumentation-starlette/src/opentelemetry/instrumentation/starlette/__init__.py

+28-5
Original file line numberDiff line numberDiff line change
@@ -294,26 +294,49 @@ def __del__(self):
294294

295295

296296
def _get_route_details(scope):
297-
"""Callback to retrieve the starlette route being served.
297+
"""
298+
Function to retrieve Starlette route from scope.
298299
299300
TODO: there is currently no way to retrieve http.route from
300301
a starlette application from scope.
301-
302302
See: https://github.com/encode/starlette/pull/804
303+
304+
Args:
305+
scope: A Starlette scope
306+
Returns:
307+
A string containing the route or None
303308
"""
304309
app = scope["app"]
305310
route = None
311+
306312
for starlette_route in app.routes:
307313
match, _ = starlette_route.matches(scope)
308314
if match == Match.FULL:
309315
route = starlette_route.path
310316
break
311317
if match == Match.PARTIAL:
312318
route = starlette_route.path
313-
# method only exists for http, if websocket
314-
# leave it blank.
315-
span_name = route or scope.get("method", "")
319+
return route
320+
321+
322+
def _get_default_span_details(scope):
323+
"""
324+
Callback to retrieve span name and attributes from scope.
325+
326+
Args:
327+
scope: A Starlette scope
328+
Returns:
329+
A tuple of span name and attributes
330+
"""
331+
route = _get_route_details(scope)
332+
method = scope.get("method", "")
316333
attributes = {}
317334
if route:
318335
attributes[SpanAttributes.HTTP_ROUTE] = route
336+
if method and route: # http
337+
span_name = f"{method} {route}"
338+
elif route: # websocket
339+
span_name = route
340+
else: # fallback
341+
span_name = method
319342
return span_name, attributes

instrumentation/opentelemetry-instrumentation-starlette/tests/test_starlette_instrumentation.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -93,15 +93,15 @@ def test_basic_starlette_call(self):
9393
spans = self.memory_exporter.get_finished_spans()
9494
self.assertEqual(len(spans), 3)
9595
for span in spans:
96-
self.assertIn("/foobar", span.name)
96+
self.assertIn("GET /foobar", span.name)
9797

9898
def test_starlette_route_attribute_added(self):
9999
"""Ensure that starlette routes are used as the span name."""
100100
self._client.get("/user/123")
101101
spans = self.memory_exporter.get_finished_spans()
102102
self.assertEqual(len(spans), 3)
103103
for span in spans:
104-
self.assertIn("/user/{username}", span.name)
104+
self.assertIn("GET /user/{username}", span.name)
105105
self.assertEqual(
106106
spans[-1].attributes[SpanAttributes.HTTP_ROUTE], "/user/{username}"
107107
)

0 commit comments

Comments
 (0)