OpenTelemetry PHP Metrics API

This document teaches how to use OpenTelemetry PHP Metrics API to measure performance with metrics. To learn how to install and configure OpenTelemetry PHP SDK, see Getting started with OpenTelemetry PHPopen in new window.

If you are not familiar with metrics terminology like timeseries or additive/synchronous/asynchronous instruments, read the introduction to OpenTelemetry Metrics first.

Getting started

To get started with metrics, you need to create a meter using MeterProvider:

$transportFactory = new OtlpHttpTransportFactory();
$reader = new ExportingReader(
    new MetricExporter(
        $transportFactory->create(
            'https://otlp.uptrace.dev/v1/metrics',
            'application/json',
            ['uptrace-dsn' => $dsn],
            TransportFactoryInterface::COMPRESSION_GZIP,
        )
    ),
    ClockFactory::getDefault()
);

$meterProvider = MeterProvider::builder()
               ->setResource($resource)
               ->addReader($reader)
               ->build();

$meter = $meterProvider->getMeter('app_or_package_name');

Using the meter, you can create instruments to measure performance. The simplest Counter instrument looks like this:

$counter = $meter->createCounter('uptrace.demo.counter_name', '', 'counter description');

for ($i = 0; $i < 1000; $i++) {
    $counter->add(1);
    if ($i % 10 === 0) {
        $reader->collect();
    }
    usleep(100);
}

For more details see otlp-metricsopen in new window example on GitHub.

Last Updated: 6/11/2023, 11:58:19 AM
Get insights and updates in your inbox: