Skip to content

Add span activate and deactivate apis #4447

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 5, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion MIGRATION_GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ Looking to upgrade from Sentry SDK 2.x to 3.x? Here's a comprehensive list of wh
- `span_id`
- `parent_span_id`: you can supply a `parent_span` instead
- The `Scope.transaction` property has been removed. To obtain the root span (previously transaction), use `Scope.root_span`. To set the root span's (transaction's) name, use `Scope.set_transaction_name()`.
- The `Scope.span =` setter has been removed.
- The `Scope.span =` setter has been removed. Please use the new `span.activate()` api instead if you want to activate a new span manually instead of using the `start_span` context manager.
- Passing a list or `None` for `failed_request_status_codes` in the Starlette integration is no longer supported. Pass a set of integers instead.
- The `span` argument of `Scope.trace_propagation_meta` is no longer supported.
- Setting `Scope.user` directly is no longer supported. Use `Scope.set_user()` instead.
Expand Down
19 changes: 12 additions & 7 deletions sentry_sdk/tracing.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,15 +270,21 @@ def __repr__(self):
)
)

def __enter__(self):
# type: () -> Span
# XXX use_span? https://github.com/open-telemetry/opentelemetry-python/blob/3836da8543ce9751051e38a110c0468724042e62/opentelemetry-api/src/opentelemetry/trace/__init__.py#L547
#
# create a Context object with parent set as current span
def activate(self):
# type: () -> None
ctx = otel_trace.set_span_in_context(self._otel_span)
# set as the implicit current context
self._ctx_token = context.attach(ctx)

def deactivate(self):
# type: () -> None
if self._ctx_token:
context.detach(self._ctx_token)
del self._ctx_token

def __enter__(self):
# type: () -> Span
self.activate()
return self

def __exit__(self, ty, value, tb):
Expand All @@ -294,8 +300,7 @@ def __exit__(self, ty, value, tb):
self.set_status(SPANSTATUS.OK)

self.finish()
context.detach(self._ctx_token)
del self._ctx_token
self.deactivate()

@property
def description(self):
Expand Down
Loading