diff --git a/src/Profiler/DatadogProfiler.php b/src/Profiler/DatadogProfiler.php index 2ca68cc..ea478a4 100644 --- a/src/Profiler/DatadogProfiler.php +++ b/src/Profiler/DatadogProfiler.php @@ -22,9 +22,17 @@ class DatadogProfiler implements ProfilerInterface private LoggerInterface $logger; + private float $sampleRate = 1.0; + public function __construct(LoggerInterface $logger) { $this->logger = $logger; + + $sampleRateString = getenv('DD_TRACE_SAMPLE_RATE'); + if(is_numeric($sampleRateString)) { + $sampleRate = floatval($sampleRateString); + $this->sampleRate = $sampleRate; + } } public function start(string $name, ?string $kind = null): void @@ -33,6 +41,10 @@ public function start(string $name, ?string $kind = null): void return; } + if($this->rateLimited()) { + return; + } + if (dd_trace_env_config('DD_TRACE_GENERATE_ROOT_SPAN')) { $this->logger->error( sprintf('You should set DD_TRACE_GENERATE_ROOT_SPAN=0 when using %s.', self::class) @@ -89,6 +101,12 @@ public function stopAndIgnore(): void GlobalTracer::set(new Tracer()); } + private function rateLimited(): bool + { + $randomFloat = mt_rand() / mt_getrandmax(); // between 0 and 1 + return $randomFloat > $this->sampleRate; + } + private function isEnabled(): bool { return \extension_loaded('ddtrace')