Skip to content

Commit bf60fdd

Browse files
mergify[bot]Kyle-Verhoogmajorgreys
authored
Use dictionary for ASGI scope storage (backport #2726) (#2755)
* Use dictionary for ASGI scope storage (#2726) (cherry picked from commit 41ae8b4) # Conflicts: # ddtrace/contrib/asgi/middleware.py # releasenotes/notes/asgi-span-19e772cb2f09ef4d.yaml * fix format Co-authored-by: Kyle Verhoog <[email protected]> Co-authored-by: Tahir H. Butt <[email protected]> Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
1 parent e1dbc65 commit bf60fdd

File tree

3 files changed

+19
-4
lines changed

3 files changed

+19
-4
lines changed

ddtrace/contrib/asgi/__init__.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,18 @@ def custom_handle_exception_span(exc, span):
3030
app = TraceMiddleware(app, handle_exception_span=custom_handle_exception_span)
3131
3232
33+
To retrieve the request span from the scope of an ASGI request use the ``span_from_scope``
34+
function::
35+
36+
from ddtrace.contrib.asgi import span_from_scope
37+
38+
def handle_request(scope, send):
39+
span = span_from_scope(scope)
40+
if span:
41+
span.set_tag(...)
42+
...
43+
44+
3345
Configuration
3446
~~~~~~~~~~~~~
3547

ddtrace/contrib/asgi/middleware.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ def _default_handle_exception_span(exc, span):
7070
def span_from_scope(scope):
7171
# type: (Mapping[str, Any]) -> Optional[Span]
7272
"""Retrieve the top-level ASGI span from the scope."""
73-
return scope.get("datadog_span")
73+
return scope.get("datadog", {}).get("request_span")
7474

7575

7676
class TraceMiddleware:
@@ -119,7 +119,7 @@ async def __call__(self, scope, receive, send):
119119
span_type=SpanTypes.WEB,
120120
)
121121

122-
scope["datadog_span"] = span
122+
scope["datadog"] = {"request_span": span}
123123

124124
if self.span_modifier:
125125
self.span_modifier(span, scope)
@@ -177,4 +177,8 @@ async def wrapped_send(message):
177177
self.handle_exception_span(exc, span)
178178
reraise(exc_type, exc_val, exc_tb)
179179
finally:
180+
try:
181+
del scope["datadog"]["request_span"]
182+
except KeyError:
183+
pass
180184
span.finish()
Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
---
22
features:
33
- |
4-
ASGI: store the ASGI span in the scope. The span is stored under the
5-
``"datadog_span"`` key and can be retrieved using the
4+
ASGI: store the ASGI span in the scope. The span can be retrieved with the
65
``ddtrace.contrib.asgi.span_from_scope`` function.

0 commit comments

Comments
 (0)