From a8a38be5ccaec616516dfdb0ee6c8a15e1b98ba8 Mon Sep 17 00:00:00 2001 From: Darrell Roberts Date: Sat, 16 May 2026 12:35:15 -0400 Subject: [PATCH] feat: Allow overriding the sampling rate. Allow for a user defined function for setting the sampling rate. Similar to Python SDK https://docs.sentry.io/platforms/python/sampling/#dynamically-sampling-error-events --- CHANGELOG.md | 4 ++++ sentry-core/src/client.rs | 14 +++++++++----- sentry-core/src/clientoptions.rs | 6 ++++++ 3 files changed, 19 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d301ced8..f3dcef87 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## 04.8.3 + +- Added `override_sampling_rate` to `ClientOptions` to allow user defined function to override sampling rate when capturing an event. ([#1128](https://github.com/getsentry/sentry-rust/pull/1128)). + ## 0.48.2 ### New Features diff --git a/sentry-core/src/client.rs b/sentry-core/src/client.rs index 63c73e8c..cfa83d0c 100644 --- a/sentry-core/src/client.rs +++ b/sentry-core/src/client.rs @@ -373,11 +373,15 @@ impl Client { scope.update_session_from_event(&event); } - if !self.sample_should_send(self.options.sample_rate) { - None - } else { - Some(event) - } + // Check if we have an override sampling rate function. + let sampling_rate = self + .options() + .override_sampling_rate + .as_ref() + .and_then(|f| f(&event)) + .unwrap_or_else(|| self.options().sample_rate); + + (self.sample_should_send(sampling_rate)).then_some(event) } /// Returns the options of this client. diff --git a/sentry-core/src/clientoptions.rs b/sentry-core/src/clientoptions.rs index cbb1f0bf..029b3b00 100644 --- a/sentry-core/src/clientoptions.rs +++ b/sentry-core/src/clientoptions.rs @@ -12,6 +12,9 @@ use crate::{Integration, IntoDsn, TransportFactory}; /// Type alias for before event/breadcrumb handlers. pub type BeforeCallback = Arc Option + Send + Sync>; +/// Type alias for override sample rate callback. +pub type OverrideSamplingRateCallback = Arc) -> Option + Send + Sync>; + /// The Session Mode of the SDK. /// /// Depending on the use-case, the SDK can be set to two different session modes: @@ -143,6 +146,8 @@ pub struct ClientOptions { pub before_send: Option>>, /// Callback that is executed for each Breadcrumb being added. pub before_breadcrumb: Option>, + /// Callback allowing for setting sampling rate based on user defined function. + pub override_sampling_rate: Option, /// Callback that is executed for each Log being added. /// /// This callback has no effect unless the `logs` feature is enabled at compile-time, as the @@ -350,6 +355,7 @@ impl Default for ClientOptions { before_send_log: None, enable_metrics: true, before_send_metric: None, + override_sampling_rate: None, } } }