Skip to content

Commit

Permalink
feat: Access transaction in current scope
Browse files Browse the repository at this point in the history
Specially when trying to add spans to automatically instrumented
transactions, users need access to the current transaction.

This gives direct access no matter how deep the code is in the
transaction/span tree.
  • Loading branch information
rhcarvalho committed Jun 25, 2020
1 parent b539ecb commit 8839f99
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 5 deletions.
24 changes: 20 additions & 4 deletions sentry_sdk/scope.py
Expand Up @@ -134,14 +134,30 @@ def fingerprint(self, value):
"""When set this overrides the default fingerprint."""
self._fingerprint = value

@_attr_setter
@property
def transaction(self):
# type: () -> Optional[Span]
"""Return the transaction (root span) in the scope."""
# XXX: update return type to Optional[Transaction]
try:
return self._span._span_recorder.spans[0]
except (AttributeError, IndexError):
return None

@transaction.setter
def transaction(self, value):
# type: (Optional[str]) -> None
"""When set this forces a specific transaction name to be set."""
# XXX: the docstring above is misleading. The implementation of
# apply_to_event prefers an existing value of event.transaction over
# anything set in the scope.
# XXX: note that with the introduction of the Scope.transaction getter,
# there is a semantic and type mismatch between getter and setter. The
# getter returns a transaction, the setter sets a transaction name.
# Without breaking version compatibility, we could make the setter set a
# transaction name or transaction (self._span) depending on the type of
# the value argument.
self._transaction = value
span = self._span
if span:
span.transaction = value

@_attr_setter
def user(self, value):
Expand Down
16 changes: 15 additions & 1 deletion tests/test_tracing.py
Expand Up @@ -3,7 +3,7 @@

import pytest

from sentry_sdk import Hub, capture_message
from sentry_sdk import Hub, capture_message, start_span
from sentry_sdk.tracing import Span


Expand Down Expand Up @@ -180,3 +180,17 @@ def before_send(event, hint):
pass

assert len(events) == 1


def test_get_transaction_from_scope(sentry_init, capture_events):
sentry_init(traces_sample_rate=1.0)
events = capture_events()

with start_span(transaction="/"):
with start_span(op="child-span"):
with start_span(op="child-child-span"):
scope = Hub.current.scope
assert scope.span.op == "child-child-span"
assert scope.transaction.transaction == "/"

assert len(events) == 1

0 comments on commit 8839f99

Please sign in to comment.