Skip to content

Commit 92da5a9

Browse files
committed
Add new_trace api to force a new trace
This reverts commit 65eaf38.
1 parent 65eaf38 commit 92da5a9

File tree

4 files changed

+41
-0
lines changed

4 files changed

+41
-0
lines changed

sentry_sdk/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
"capture_exception",
2323
"capture_message",
2424
"continue_trace",
25+
"new_trace",
2526
"flush",
2627
"get_baggage",
2728
"get_client",

sentry_sdk/api.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@
4848
"capture_exception",
4949
"capture_message",
5050
"continue_trace",
51+
"new_trace",
5152
"flush",
5253
"get_baggage",
5354
"get_client",
@@ -315,6 +316,15 @@ def continue_trace(environ_or_headers: dict[str, Any]) -> Generator[None, None,
315316
yield
316317

317318

319+
@contextmanager
320+
def new_trace() -> Generator[None, None, None]:
321+
"""
322+
Force creation of a new trace.
323+
"""
324+
with get_isolation_scope().new_trace():
325+
yield
326+
327+
318328
@scopemethod
319329
def start_session(
320330
session_mode: str = "application",

sentry_sdk/opentelemetry/scope.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
TraceFlags,
1616
TraceState,
1717
use_span,
18+
INVALID_SPAN,
1819
)
1920

2021
from sentry_sdk.opentelemetry.consts import (
@@ -89,6 +90,15 @@ def continue_trace(
8990
with use_span(NonRecordingSpan(span_context)):
9091
yield
9192

93+
@contextmanager
94+
def new_trace(self) -> Generator[None, None, None]:
95+
"""
96+
Force creation of a new trace.
97+
"""
98+
self.generate_propagation_context()
99+
with use_span(INVALID_SPAN):
100+
yield
101+
92102
def _incoming_otel_span_context(self) -> Optional[SpanContext]:
93103
if self._propagation_context is None:
94104
return None

tests/test_api.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from sentry_sdk import (
66
capture_exception,
77
continue_trace,
8+
new_trace,
89
get_baggage,
910
get_client,
1011
get_current_span,
@@ -96,6 +97,25 @@ def test_continue_trace(sentry_init):
9697
}
9798

9899

100+
def test_new_trace(sentry_init, capture_events):
101+
sentry_init(traces_sample_rate=1.0)
102+
events = capture_events()
103+
104+
with start_span(name="parent"):
105+
with start_span(name="child"):
106+
with new_trace():
107+
with start_span(name="parent2"):
108+
with start_span(name="child2"):
109+
pass
110+
111+
assert len(events) == 2
112+
(tx1, tx2) = events
113+
assert tx1["transaction"] == "parent2"
114+
assert tx1["spans"][0]["description"] == "child2"
115+
assert tx2["transaction"] == "parent"
116+
assert tx2["spans"][0]["description"] == "child"
117+
118+
99119
def test_is_initialized():
100120
assert not is_initialized()
101121

0 commit comments

Comments
 (0)