getsentry / sentry-python

The official Python SDK for Sentry.io
https://sentry.io/for/python/
MIT License
1.93k stars 510 forks source link

`start_span` API not as context manager #3489

Open sentrivana opened 2 months ago

sentrivana commented 2 months ago

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

sl0thentr0py commented 2 months ago

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

antonpirker commented 2 months ago

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()