Skip to content

Commit

Permalink
Add timing span when emiting a timing metric (#1717)
Browse files Browse the repository at this point in the history
Co-authored-by: Alex Bouma <alex@bouma.me>
  • Loading branch information
cleptric and stayallive committed May 24, 2024
1 parent d12ed37 commit e26ecf8
Showing 1 changed file with 28 additions and 14 deletions.
42 changes: 28 additions & 14 deletions src/Metrics/Metrics.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@
use Sentry\Metrics\Types\DistributionType;
use Sentry\Metrics\Types\GaugeType;
use Sentry\Metrics\Types\SetType;
use Sentry\Tracing\SpanContext;

use function Sentry\trace;

class Metrics
{
Expand Down Expand Up @@ -142,21 +145,32 @@ public function timing(
array $tags = [],
int $stackLevel = 0
) {
$startTimestamp = microtime(true);

$result = $callback();

$this->aggregator->add(
DistributionType::TYPE,
$key,
microtime(true) - $startTimestamp,
MetricsUnit::second(),
$tags,
(int) $startTimestamp,
$stackLevel
return trace(
function () use ($callback, $key, $tags, $stackLevel) {
$startTimestamp = microtime(true);

$result = $callback();

/**
* Emitting the metric here, will attach it to the
* "metric.timing" span.
*/
$this->aggregator->add(
DistributionType::TYPE,
$key,
microtime(true) - $startTimestamp,
MetricsUnit::second(),
$tags,
(int) $startTimestamp,
$stackLevel + 4 // the `trace` helper adds 4 additional stack frames
);

return $result;
},
SpanContext::make()
->setOp('metric.timing')
->setDescription($key)
);

return $result;
}

public function flush(): ?EventId
Expand Down

0 comments on commit e26ecf8

Please sign in to comment.