Skip to content

Commit 5b05589

Browse files
feat: non-experimental before_send_metric option (#5064)
Add a stable `before_send_metric` option. If no value is specified, the existing experimental callback is invoked instead.
1 parent 6a76cc5 commit 5b05589

File tree

3 files changed

+43
-1
lines changed

3 files changed

+43
-1
lines changed

sentry_sdk/consts.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1012,6 +1012,7 @@ def __init__(
10121012
before_send_log=None, # type: Optional[Callable[[Log, Hint], Optional[Log]]]
10131013
trace_ignore_status_codes=frozenset(), # type: AbstractSet[int]
10141014
enable_metrics=True, # type: bool
1015+
before_send_metric=None, # type: Optional[Callable[[Metric, Hint], Optional[Metric]]]
10151016
):
10161017
# type: (...) -> None
10171018
"""Initialize the Sentry SDK with the given parameters. All parameters described here can be used in a call to `sentry_sdk.init()`.

sentry_sdk/utils.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2060,4 +2060,6 @@ def get_before_send_metric(options):
20602060
if options is None:
20612061
return None
20622062

2063-
return options["_experiments"].get("before_send_metric")
2063+
return options.get("before_send_metric") or options["_experiments"].get(
2064+
"before_send_metric"
2065+
)

tests/test_metrics.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,45 @@ def test_metrics_tracing_without_performance(sentry_init, capture_envelopes):
168168
def test_metrics_before_send(sentry_init, capture_envelopes):
169169
before_metric_called = False
170170

171+
def _before_metric(record, hint):
172+
nonlocal before_metric_called
173+
174+
assert set(record.keys()) == {
175+
"timestamp",
176+
"trace_id",
177+
"span_id",
178+
"name",
179+
"type",
180+
"value",
181+
"unit",
182+
"attributes",
183+
}
184+
185+
if record["name"] == "test.skip":
186+
return None
187+
188+
before_metric_called = True
189+
return record
190+
191+
sentry_init(
192+
before_send_metric=_before_metric,
193+
)
194+
envelopes = capture_envelopes()
195+
196+
sentry_sdk.metrics.count("test.skip", 1)
197+
sentry_sdk.metrics.count("test.keep", 1)
198+
199+
get_client().flush()
200+
201+
metrics = envelopes_to_metrics(envelopes)
202+
assert len(metrics) == 1
203+
assert metrics[0]["name"] == "test.keep"
204+
assert before_metric_called
205+
206+
207+
def test_metrics_experimental_before_send(sentry_init, capture_envelopes):
208+
before_metric_called = False
209+
171210
def _before_metric(record, hint):
172211
nonlocal before_metric_called
173212

0 commit comments

Comments
 (0)