Skip to content

Patch TracerProvider if it already exists #4455

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 11 commits into from
Jun 12, 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
30 changes: 27 additions & 3 deletions sentry_sdk/opentelemetry/tracing.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
SentrySampler,
SentrySpanProcessor,
)
from sentry_sdk.utils import logger


def patch_readable_span():
Expand All @@ -28,8 +29,31 @@ def sentry_patched_readable_span(self):

def setup_sentry_tracing():
# type: () -> None
provider = TracerProvider(sampler=SentrySampler())
provider.add_span_processor(SentrySpanProcessor())
trace.set_tracer_provider(provider)
# TracerProvider can only be set once. If we're the first ones setting it,
# there's no issue. If it already exists, we need to patch it.
from opentelemetry.trace import _TRACER_PROVIDER

if _TRACER_PROVIDER is not None:
logger.debug("[Tracing] Detected an existing TracerProvider, patching")
tracer_provider = _TRACER_PROVIDER
tracer_provider.sampler = SentrySampler() # type: ignore[attr-defined]

else:
logger.debug("[Tracing] No TracerProvider set, creating a new one")
tracer_provider = TracerProvider(sampler=SentrySampler())
trace.set_tracer_provider(tracer_provider)

try:
existing_span_processors = (
tracer_provider._active_span_processor._span_processors # type: ignore[attr-defined]
)
except Exception:
existing_span_processors = []

for span_processor in existing_span_processors:
if isinstance(span_processor, SentrySpanProcessor):
break
else:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lol til there is for else in python

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah this is kinda obscure. I used to avoid it for that reason but I somewhat like it now

tracer_provider.add_span_processor(SentrySpanProcessor()) # type: ignore[attr-defined]

set_global_textmap(SentryPropagator())
2 changes: 1 addition & 1 deletion sentry_sdk/tracing.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ def __init__(
If otel_span is passed explicitly, just acts as a proxy.

If span is passed explicitly, use it. The only purpose of this param
if backwards compatibility with start_transaction(transaction=...).
is backwards compatibility with start_transaction(transaction=...).

If only_if_parent is True, just return an INVALID_SPAN
and avoid instrumentation if there's no active parent span.
Expand Down
14 changes: 14 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@
import os
import socket
import warnings
from opentelemetry import trace as otel_trace

try:
from opentelemetry.util._once import Once
except ImportError:
Once = None
from threading import Thread
from http.server import BaseHTTPRequestHandler, HTTPServer

Expand Down Expand Up @@ -73,6 +79,14 @@ def clean_scopes():
setup_initial_scopes()


@pytest.fixture(autouse=True)
def clear_tracer_provider():
"""Reset TracerProvider so that we can set it up from scratch."""
if Once is not None:
otel_trace._TRACER_PROVIDER_SET_ONCE = Once()
otel_trace._TRACER_PROVIDER = None


@pytest.fixture(autouse=True)
def internal_exceptions(request):
errors = []
Expand Down
Loading