Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Respect Datadog DD_TRACE_SAMPLE_RATE rate limiting environment variable #19

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions src/Profiler/DatadogProfiler.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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')
Expand Down
Loading