Skip to content

Commit c8d5799

Browse files
authored
Add async span context manager (#4680)
Add an async span context manager to allow for cleaner nesting in async code. Currently only delegates to the synchronous context manager. Fixes GH-2007
1 parent 8467d30 commit c8d5799

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

sentry_sdk/tracing.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -278,6 +278,14 @@ def __exit__(
278278
self.finish()
279279
self.deactivate()
280280

281+
async def __aenter__(self) -> Span:
282+
return self.__enter__()
283+
284+
async def __aexit__(
285+
self, ty: Optional[Any], value: Optional[Any], tb: Optional[Any]
286+
) -> None:
287+
return self.__exit__(ty, value, tb)
288+
281289
@property
282290
def description(self) -> Optional[str]:
283291
return self.get_attribute(SentrySpanAttribute.DESCRIPTION)

tests/tracing/test_integration_tests.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import re
22
import sys
3+
import asyncio
34
from unittest import mock
45

56
import pytest
@@ -280,3 +281,26 @@ def test_good_sysexit_doesnt_fail_transaction(
280281
assert "status" not in span.get("tags", {})
281282
assert "status" not in event.get("tags", {})
282283
assert event["contexts"]["trace"]["status"] == "ok"
284+
285+
286+
@pytest.mark.asyncio
287+
async def test_async_context_manager(sentry_init, capture_events):
288+
"""Test that spans work as async context managers"""
289+
sentry_init(traces_sample_rate=1.0)
290+
events = capture_events()
291+
292+
async with start_span(name="async_transaction") as transaction:
293+
transaction.set_status(SPANSTATUS.OK)
294+
async with start_span(op="async.task", name="async_operation") as span:
295+
span.set_tag("test", "async")
296+
await asyncio.sleep(0.001)
297+
298+
assert len(events) == 1
299+
event = events[0]
300+
assert event["transaction"] == "async_transaction"
301+
assert event["contexts"]["trace"]["status"] == "ok"
302+
assert len(event["spans"]) == 1
303+
span = event["spans"][0]
304+
assert span["op"] == "async.task"
305+
assert span["description"] == "async_operation"
306+
assert span["tags"]["test"] == "async"

0 commit comments

Comments
 (0)