~/docs
Resonate
Resonate
0.x 0.3.0, current
Fledge APM
Toggle sidebar
Fledge APM
webpatser/fledge-apm 0.3.0

Fledge APM 0.x

Examples

Custom spans, manual start and end, back-dated spans and flushing with the Tracer.

All examples resolve Fledge\Apm\Tracer from the container. When APM is disabled it wraps the OpenTelemetry no-op tracer, so the same code runs with no cost.

A span around a closure

span() runs the closure inside a child span of the fiber's current span. An exception is recorded on the span, marks it failed and is rethrown.

<?php
 
use Fledge\Apm\ActiveSpan;
use Fledge\Apm\Tracer;
use OpenTelemetry\API\Trace\SpanKind;
 
$tracer = app(Tracer::class);
 
$total = $tracer->span(
'report.build',
function (ActiveSpan $span) {
$span->setAttribute('report.rows', 250);
 
return buildReport();
},
SpanKind::KIND_INTERNAL,
['report.type' => 'monthly'],
);

Start and end in different places

Use startSpan() when start and end live in different callbacks of the same fiber. It is the current span of the fiber until end(), so spans started meanwhile nest under it. Start and end it in the same fiber.

<?php
 
use Fledge\Apm\Tracer;
use OpenTelemetry\API\Trace\SpanKind;
 
$tracer = app(Tracer::class);
 
$span = $tracer->startSpan('import.run', SpanKind::KIND_INTERNAL, ['import.source' => 'csv']);
 
try {
runImport();
} catch (Throwable $exception) {
$span->recordException($exception);
 
throw $exception;
} finally {
$span->end();
}

recordException() redacts query bindings like the built-in instrumentations do, and setError('reason') marks the span failed without an exception.

Record a finished span

recordSpan() adds a span that already ran, with explicit timestamps in epoch nanoseconds. Tracer::now() and Tracer::nanosAgo() give values on the clock spans use.

<?php
 
use Fledge\Apm\Tracer;
use OpenTelemetry\API\Trace\SpanKind;
 
$tracer = app(Tracer::class);
 
$start = Tracer::nanosAgo(35.5); // started 35.5 ms ago
 
$tracer->recordSpan(
'legacy.lookup',
$start,
Tracer::now(),
SpanKind::KIND_CLIENT,
['lookup.id' => 42],
);

Parallel work in fibers

A fiber started with async() inherits the span of whoever started it, so the spans below are siblings under page.load.

<?php
 
use Fledge\Apm\Tracer;
 
use function Fledge\Async\async;
 
$tracer = app(Tracer::class);
 
$tracer->span('page.load', function () use ($tracer) {
$a = async(fn () => $tracer->span('load.sidebar', fn () => loadSidebar()));
$b = async(fn () => $tracer->span('load.feed', fn () => loadFeed()));
 
return [$a->await(), $b->await()];
});

Mark a trace as failed and flush

markRootFailed() sets the local root span to error, so a trace the ratio sampler dropped is still exported as long as keep.errors is on (the default). flush() exports everything buffered within the flush budget and returns whether it succeeded.

<?php
 
use Fledge\Apm\Tracer;
 
$tracer = app(Tracer::class);
 
$tracer->markRootFailed('payment provider unreachable');
 
if ($tracer->enabled()) {
$tracer->flush();
}