Skip to content

API reference

API reference

Everything hangs off the Cbox\Telemetry\Facades\Telemetry facade.

Metrics

// Counter — monotonic, shared across processes
Telemetry::counter('orders.created', 'Orders created')->inc();
Telemetry::counter('orders.created')->inc(5, ['tenant' => 'acme']);

// Push gauge — set, or adjust up/down (active connections, in-flight jobs)
Telemetry::gauge('cache.warmed_keys')->set(1240);
Telemetry::gauge('jobs.in_flight')->increment(labels: ['queue' => 'default']);
Telemetry::gauge('jobs.in_flight')->decrement(labels: ['queue' => 'default']);

// Observable gauge — callback at scrape time, single or multi-series
Telemetry::gauge('queue.depth', fn () => Queue::size(), unit: '{jobs}');
Telemetry::gauge('queue.depth', fn () => [
    [12, ['queue' => 'default']],
    [3,  ['queue' => 'mail']],
]);

// Histogram — distributions, with closure timing
Telemetry::histogram('checkout.duration', unit: 's')->record($seconds);
Telemetry::histogram('import.duration', buckets: [0.1, 0.5, 1], unit: 's')
    ->time(fn () => $importer->run());

Traces

// Closure form — ends, records exceptions, rethrows
$result = Telemetry::span('billing.recalculate', function ($span) {
    $span->setAttribute('tenant.id', $id);

    return $service->run();
});

// Manual form
$span = Telemetry::span('phase.one', attributes: ['shard' => 3]);
$span->addEvent('checkpoint', ['rows' => 5000]);
$span->recordException($e);
$span->setStatus(SpanStatus::Ok);
$span->updateName('phase.one retried');
$span->end();

// Context
Telemetry::currentSpan();          // ?Span
Telemetry::traceId();              // ?string
Telemetry::traceparent();          // ?string — W3C header value
Telemetry::continueTrace($header); // continue a remote trace
Telemetry::resetContext();         // forget the active trace
Telemetry::directives()->add(Directive::user(42)->profile()->for(minutes: 120)); // keep this slice for a while
Telemetry::sample(true);           // force-keep this trace (or a rate: sample(0.01)) — e.g. for admins
Telemetry::captureLaravelContext(['tenant']); // read Laravel Context onto root spans/logs/exceptions (= instrument.laravel_context)

// Requests left uninstrumented (merged with instrument.http_ignore_paths)
Telemetry::ignorePaths(['telemetry-ui', 'telemetry-ui/*']); // Str::is globs, no leading slash
Telemetry::ignoredPaths();         // list<string> — config + registered
Telemetry::ignoresPath('health');  // bool

// Outbound propagation
Http::withTraceparent()->post($url, $payload);

// A queued job (listener, mailable, notification) that starts its own
// trace, linked to the dispatching span — or list it in queue.linked_traces
final class RebuildSearchIndex implements ShouldQueue, StartsLinkedTrace {} // Cbox\Telemetry\Contracts

Events & logs

Telemetry::event('autoscale.decision', ['workers' => 7]);
// config/logging.php — ship logs as trace-correlated OTLP log records
'telemetry' => ['driver' => 'telemetry', 'level' => 'info'],

Providers & exporters

Telemetry::provider(new QueueMetricsProvider);          // contract-based
Telemetry::contributes('my-app', fn (Registry $r) => ...); // inline
Telemetry::addExporter(new ClickhouseExporter(...));    // runtime exporter

Export & introspection

Telemetry::collect();       // list<MetricFamily> — what a scrape sees
Telemetry::flush();         // export buffered spans + events now → ExportReport
Telemetry::flushMetrics();  // push metrics to exporters now → ExportReport
Telemetry::enabled();       // bool
Telemetry::handleExceptionsUsing(fn (Throwable $e) => ...);

Both flushes return an ExportReport saying what each exporter did with the batch — they still never throw, but the outcome is no longer thrown away either:

$report = Telemetry::flushMetrics();

$report->items;         // metric families offered
$report->attempted();   // exporters the batch was sent to
$report->accepted();    // exporters that took it
$report->successful();  // nothing failed and nothing was rejected
$report->summary();     // "2 of 3 exporters accepted the batch"

foreach ($report->problems() as $problem) {
    $problem->exporter;         // "otlp"
    $problem->status;           // ExportStatus::Failed
    $problem->describe();       // 'rejected: HTTP 400: {"message":"…"}'
}

Testing

$fake = Telemetry::fake();

$fake->assertCounterIncremented('orders.created', ['tenant' => 'acme']);
$fake->assertCounterNotIncremented('orders.cancelled');
$fake->assertGaugeSet('cache.warmed_keys');
$fake->assertHistogramRecorded('checkout.duration');
$fake->assertSpanRecorded('billing.recalculate', fn ($span) => ...);
$fake->assertSpanNotRecorded('other.work');
$fake->assertEventEmitted('autoscale.decision', fn ($event) => ...);
$fake->assertEventNotEmitted('never.happened');

$fake->counterValue('orders.created', ['tenant' => 'acme']);
$fake->gaugeValue('queue.depth');
$fake->histogramCount('checkout.duration');
$fake->recordedSpans('billing.recalculate');
$fake->recordedEvents();

// Every recorded series — labels and cardinality, not just presence.
$fake->recordedMetrics('orders.created')
    ->assertLabelValues('tenant', ['acme', 'globex'])   // exactly these
    ->assertCardinalityBelow(50)
    ->assertLabelCardinalityBelow('tenant', 10)
    ->assertSeriesCount(2);

$fake->recordedMetrics()->forMetric('orders.created')->labelValues('tenant');
$fake->recordedMetrics()->labelCardinality();           // ['tenant' => 2]
$fake->metricLabelValues('orders.created', 'tenant');
$fake->assertMetricLabelValues('orders.created', 'tenant', ['acme', 'globex']);

// Performance budgets — read from query spans, root tallies and the
// N+1/duplicate detector; checked per recorded trace, failures list each
// SQL shape with its count and code.* origin.
$this->get('/orders');
Telemetry::assertQueryCount('<=', 10);       // or assertQueryCount(3) for exactly
Telemetry::assertNoNPlusOne();
Telemetry::assertNoDuplicateQueries();
Telemetry::assertNoSlowQueries(?$thresholdMs);
Telemetry::assertMaxDuration(200);           // ms, root span
Telemetry::budget(fn () => ..., queries: 10, ms: 200, allowNPlusOne: false, allowDuplicates: false);
Telemetry::profiles();                       // list<PerformanceProfile>, one per trace

Artisan

php artisan telemetry:doctor                   # verify store, exporters, config (exits 1 on a failed check)
php artisan telemetry:flush [--wipe]           # export metrics and drain the OTLP spool (exits 1 on a rejected batch)
php artisan telemetry:monitor [--once]         # sample host + process metrics (node_exporter analog)
php artisan telemetry:deploy [--id=] [--notes=] # emit a deployment marker event (dashboard annotations)
php artisan telemetry:dashboards [--export=]   # install the Grafana dashboards
php artisan about                              # shows the Telemetry section

Source timestamps for external metric batches

When an integration constructs MetricFamily objects for an exporter, pass the optional trailing timeUnixNano argument to preserve the source observation time:

$family = new MetricFamily(
    definition: new MetricDefinition('runtime.cpu.time', MetricType::Counter, unit: 's'),
    samples: [new Sample(['pod.uid' => $podUid], $cumulativeSeconds)],
    startUnixNano: $sourceEpoch,
    timeUnixNano: $sourceObservation,
);

Both timestamps are Unix nanoseconds. Supply valid source times and an epoch no later than the observation. OTLP preserves the observation timestamp as an int64 string for counters, up/down counters, gauges and histograms. With null (the default), existing export-time behavior is unchanged. All series in one family share this timestamp; use separate families for observations taken at different times. Serializing or retrying the same family does not restamp its source time.

This low-level export metadata does not change instrument/store sampling APIs, add buffering, deduplicate backend rows, or turn the exporter into a billing ledger. The Prometheus renderer retains normal scrape-time behavior.