Manually instrument PHP applications for Splunk Observability Cloud 🔗
The OpenTelemetry instrumentation for PHP provides a base you can build on by adding your own manual instrumentation. By using both automatic and manual instrumentation, you can better instrument the logic and functionality of your applications, clients, and frameworks.
Create custom spans and traces 🔗
To create custom spans and traces, follow these steps:
Create a
TracerProvider
entry point if you aren’t using an instrumentation library:$tracerProvider = Globals::tracerProvider();
Create a tracer:
// Acquire the tracer only where needed $tracer = $tracerProvider->getTracer( 'instrumentation-scope-name', // Name (Required) 'instrumentation-scope-version', // Version 'http://example.com/my-schema', // Schema URL ['foo' => 'bar'] // Resource attributes );
Create spans:
<?php public function roll($rolls) { $span = $this->tracer->spanBuilder("rollTheDice")->startSpan(); $result = []; for ($i = 0; $i < $rolls; $i++) { $result[] = $this->rollOnce(); } $span->end(); return $result; }
Optionally, set attributes to enrich your spans’s metadata:
$span->setAttribute(TraceAttributes::CODE_FUNCTION, 'rollOnce'); $span->setAttribute(TraceAttributes::CODE_FILEPATH, __FILE__);
Create custom metrics 🔗
To create custom metrics, follow these steps:
Add the following dependencies:
use OpenTelemetry\SDK\Metrics\MetricExporter\ConsoleMetricExporterFactory; use OpenTelemetry\SDK\Metrics\MeterProvider; use OpenTelemetry\SDK\Metrics\MetricReader\ExportingReader; require 'vendor/autoload.php';
Create a
MeterProvider
entry point:$meterProvider = Globals::meterProvider();
Create an instrument. For example, a gauge:
$queue = [ 'job1', 'job2', 'job3', ]; $reader = $meterProvider ->getMeter('demo_meter') ->createObservableGauge('queued', 'jobs', 'The number of jobs enqueued') ->observe(static function (ObserverInterface $observer) use (&$queue): void { $observer->observe(count($queue)); }); $reader->collect(); array_pop($queue); $reader->collect();