Skip to content

Commit fbf7d74

Browse files
Idea for reporting traces_sampler errors
My proposal for reporting `traces_sampler` errors. Do you all think this makes sense? Fixes #2582
1 parent 5dcda1d commit fbf7d74

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

sentry_sdk/tracing.py

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from sentry_sdk.consts import INSTRUMENTER, SPANSTATUS, SPANDATA
88
from sentry_sdk.profiler.continuous_profiler import get_profiler_id
99
from sentry_sdk.utils import (
10+
event_from_exception,
1011
get_current_thread_meta,
1112
is_valid_sample_rate,
1213
logger,
@@ -1143,9 +1144,12 @@ def _set_initial_sampling_decision(self, sampling_context):
11431144
# we would have bailed already if neither `traces_sampler` nor
11441145
# `traces_sample_rate` were defined, so one of these should work; prefer
11451146
# the hook if so
1147+
traces_sampler_rate = _rate_from_traces_sampler(
1148+
client.options.get("traces_sampler"), sampling_context
1149+
)
11461150
sample_rate = (
1147-
client.options["traces_sampler"](sampling_context)
1148-
if callable(client.options.get("traces_sampler"))
1151+
traces_sampler_rate
1152+
if traces_sampler_rate is not None
11491153
else (
11501154
# default inheritance behavior
11511155
sampling_context["parent_sampled"]
@@ -1341,6 +1345,23 @@ async def my_async_function():
13411345
return start_child_span_decorator
13421346

13431347

1348+
def _rate_from_traces_sampler(traces_sampler, sampling_context):
1349+
# type: (Any, SamplingContext) -> Optional[Any]
1350+
if not callable(traces_sampler):
1351+
return None
1352+
1353+
try:
1354+
return traces_sampler(sampling_context)
1355+
except Exception as e:
1356+
event, hint = event_from_exception(
1357+
e,
1358+
mechanism={"type": "traces_sampler", "handled": False},
1359+
)
1360+
sentry_sdk.capture_event(event, hint)
1361+
logger.error("Unhandled exception in traces_sampler", exc_info=True)
1362+
return None
1363+
1364+
13441365
# Circular imports
13451366

13461367
from sentry_sdk.tracing_utils import (

0 commit comments

Comments
 (0)