Skip to content

Commit 99a8a8a

Browse files
committed
Merge branch 'radostyle-datadog-rate-limit'
2 parents 0bc1b61 + 9fc9ac6 commit 99a8a8a

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

src/Profiler/DatadogProfiler.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,17 @@ class DatadogProfiler implements ProfilerInterface
2222

2323
private LoggerInterface $logger;
2424

25+
private float $sampleRate = 1.0;
26+
2527
public function __construct(LoggerInterface $logger)
2628
{
2729
$this->logger = $logger;
30+
31+
$sampleRateString = getenv('DD_TRACE_SAMPLE_RATE');
32+
if(is_numeric($sampleRateString)) {
33+
$sampleRate = floatval($sampleRateString);
34+
$this->sampleRate = $sampleRate;
35+
}
2836
}
2937

3038
public function start(string $name, ?string $kind = null): void
@@ -33,6 +41,10 @@ public function start(string $name, ?string $kind = null): void
3341
return;
3442
}
3543

44+
if($this->rateLimited()) {
45+
return;
46+
}
47+
3648
if (dd_trace_env_config('DD_TRACE_GENERATE_ROOT_SPAN')) {
3749
$this->logger->error(
3850
sprintf('You should set DD_TRACE_GENERATE_ROOT_SPAN=0 when using %s.', self::class)
@@ -89,6 +101,12 @@ public function stopAndIgnore(): void
89101
GlobalTracer::set(new Tracer());
90102
}
91103

104+
private function rateLimited(): bool
105+
{
106+
$randomFloat = mt_rand() / mt_getrandmax(); // between 0 and 1
107+
return $randomFloat > $this->sampleRate;
108+
}
109+
92110
private function isEnabled(): bool
93111
{
94112
return \extension_loaded('ddtrace')

0 commit comments

Comments
 (0)