sentry-python icon indicating copy to clipboard operation
sentry-python copied to clipboard

`start_span` API not as context manager

Open sentrivana opened this issue 1 year ago • 2 comments

Problem

Before POTel, you could do:

span = start_span(...)
sentry_sdk.get_current_scope().span = span   # forgot this initially, in case you're confused by the comments
# do stuff
span.finish()

i.e., start and finish a span without using a context manager.

With the current POTel design, this would create an inactive span (not attached to the current span as a child span) because the context attach/detach happens in __enter__ and __exit__, respectively.

This might break a lot of setups -> we should find a way to still support this, while also giving people the possibility to create inactive spans.

(Same for start_transaction.)

Solution

  • make the code snippet above work in POTel to not break users (i.e., implement the scope.span setter) and deprecate it
  • add a span.activate() method that is a user-friendly equivalent of setting the span on the scope

sentrivana avatar Sep 02 '24 11:09 sentrivana

in the older way, you would still have to add the span to scope manually, so the behaviour is kinda the same. https://github.com/getsentry/sentry-python/blob/cd15bff1a890d0917793eec01c8078b6b3560920/sentry_sdk/tracing.py#L360-L366

sl0thentr0py avatar Sep 02 '24 11:09 sl0thentr0py

Some of our integrations call span.__enter__() and span.__exit__() manually, because a context manager would not work: https://github.com/getsentry/sentry-python/blob/antonpirker/potel/sampler/sentry_sdk/integrations/anthropic.py#L100

Maybe we should make this an official api? Like:

span = start_span(...)
span.activate()
# do stuff
span.finish()

antonpirker avatar Sep 02 '24 11:09 antonpirker

If anyone is missing this functionality let's tell them to use __enter__/__exit__ directly or use the underlying OTel API.

sentrivana avatar Jan 14 '25 12:01 sentrivana

Maybe check docs if we're promoting start_span without the context manager and update them @sentrivana

sentrivana avatar Jan 14 '25 12:01 sentrivana