OpenTelemetry metrics in PHP: instrument Laravel HTTP requests
Record Laravel request counts and durations with the PHP OpenTelemetry Metrics SDK. Test route labels, PHP-FPM request shutdown, and OTLP/HTTP Protobuf export.
A Laravel checkout can return 503 while the PHP-FPM pool still looks healthy. Count the responses Laravel actually returns, and measure how long the application took to produce them. Label both by the matched route template so a request for each new order ID does not create a new metric series.
Give the request a local OTLP destination
This example uses Laravel 13, which requires PHP 8.3 or later. The pinned OpenTelemetry SDK and OTLP exporter themselves require PHP 8.2 or later. It uses Guzzle and the Composer Protobuf package, so this manual instrumentation does not need the OpenTelemetry auto-instrumentation extension. From the root of an existing Laravel project, install the packages. OpenTelemetry PHP instrumentation
composer require open-telemetry/sdk:1.16.1 \
open-telemetry/exporter-otlp:1.5.0 \
guzzlehttp/guzzle:7.16.1 google/protobuf:5.36.2
Save this as collector.yaml and start Collector Contrib with otelcol-contrib --config=collector.yaml. The OTLP/HTTP receiver binds to loopback. The debug exporter lets you inspect the metric points before connecting a backend.
receivers:
otlp:
protocols:
http:
endpoint: 127.0.0.1:14318
exporters:
debug:
verbosity: detailed
service:
pipelines:
metrics:
receivers: [otlp]
exporters: [debug]
Record the response Laravel sends
Put the middleware in app/Http/Middleware/OpenTelemetryMetrics.php. The monotonic timer covers downstream Laravel processing. It excludes sending the response body and exporting telemetry. Store the duration on the request because Laravel can resolve a fresh middleware instance for terminate(). The response passed to that method supplies the final status, including a handled HTTP exception. Laravel terminable middleware
<?php
namespace App\Http\Middleware;
use Closure;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\HttpFactory;
use Illuminate\Http\Request;
use OpenTelemetry\Contrib\Otlp\MetricExporter;
use OpenTelemetry\SDK\Common\Attribute\Attributes;
use OpenTelemetry\SDK\Common\Export\Http\PsrTransportFactory;
use OpenTelemetry\SDK\Metrics\Data\Temporality;
use OpenTelemetry\SDK\Metrics\MeterProvider;
use OpenTelemetry\SDK\Metrics\MetricReader\ExportingReader;
use OpenTelemetry\SDK\Resource\ResourceInfo;
use Symfony\Component\HttpFoundation\Response;
use Throwable;
final class OpenTelemetryMetrics
{
private const DURATION = '_otel_demo_duration_seconds';
public function handle(Request $request, Closure $next): Response
{
$started = hrtime(true);
try {
return $next($request);
} finally {
$request->attributes->set(self::DURATION, (hrtime(true) - $started) / 1e9);
}
}
public function terminate(Request $request, Response $response): void
{
$duration = $request->attributes->get(self::DURATION);
if (!is_float($duration)) {
return;
}
$method = $request->method();
$knownMethods = ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'TRACE', 'PATCH'];
$attributes = [
'http.request.method' => in_array($method, $knownMethods, true) ? $method : '_OTHER',
'http.response.status_code' => $response->getStatusCode(),
];
if ($route = $request->route()) {
$attributes['http.route'] = '/' . ltrim($route->uri(), '/');
}
try {
$factory = new HttpFactory();
$client = new Client(['timeout' => 0.25]);
$transport = (new PsrTransportFactory($client, $factory, $factory))->create(
getenv('OTEL_EXPORTER_OTLP_METRICS_ENDPOINT') ?: 'http://127.0.0.1:14318/v1/metrics',
'application/x-protobuf',
maxRetries: 0,
);
$reader = new ExportingReader(new MetricExporter($transport, Temporality::DELTA));
$provider = MeterProvider::builder()
->setResource(ResourceInfo::create(Attributes::create(['service.name' => 'checkout-php'])))
->addReader($reader)
->build();
try {
$meter = $provider->getMeter('example.checkout');
$requests = $meter->createCounter('app.http.server.requests', '{request}');
$latency = $meter->createHistogram('app.http.server.duration', 's', advisory: [
'ExplicitBucketBoundaries' => [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5],
]);
$requests->add(1, $attributes);
$latency->record($duration, $attributes);
} finally {
if (!$provider->shutdown()) {
error_log('OpenTelemetry metrics export did not complete');
}
}
} catch (Throwable $error) {
error_log('OpenTelemetry metrics export failed: ' . $error::class);
}
}
}
Merge this into the existing withMiddleware callback in bootstrap/app.php.
->withMiddleware(function (\Illuminate\Foundation\Configuration\Middleware $middleware): void {
$middleware->prepend(\App\Http\Middleware\OpenTelemetryMetrics::class);
})
The custom metric names keep the example distinct from standard HTTP metrics an agent may already emit. http.route holds the matched template, such as /otel-probe/{order}. If the router has no match, omit it. An actual path, a query string or a customer identifier would make the label grow with traffic. HTTP metric semantic conventions
Read the two exports side by side
In an initialized, disposable Laravel project, generate a local app key with php artisan key:generate if needed. Add the following route to routes/web.php. Run SESSION_DRIVER=array php artisan serve --host=127.0.0.1 --port=8000, then call the two URLs.
\Illuminate\Support\Facades\Route::get('/otel-probe/{order}', function (string $order) {
abort_if($order === 'fail', 503);
return response()->noContent();
});
curl -sS -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8000/otel-probe/alpha
curl -sS -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8000/otel-probe/fail
Expect 204 and 503. In Collector output, each request should contribute a delta of one and one histogram observation. The status codes should differ and the route template should match. For a 5xx ratio, sum the 5xx increments and divide by the sum of all request increments over the same window and scope. The example uses explicit duration boundaries from 5 ms to 2.5 s. Set them around the latency thresholds you care about. To estimate P95, use the duration distribution with its bucket counts. A request counter alone contains no latency information.
If the next destination is Guance, use the same two requests to check what the backend stored. This code reads the full URL from the process environment variable OTEL_EXPORTER_OTLP_METRICS_ENDPOINT. DataKit's default OTLP/HTTP endpoint uses port 9529 and path /otel/v1/metrics, with a Protobuf payload. Configure private connectivity, TLS and authentication for the actual deployment. Check how the destination handles delta temporality and histogram buckets before you rely on a dashboard query. DataKit OpenTelemetry input
Decide where metrics should accumulate
PHP-FPM reuses worker processes, but the SDK objects in an ordinary request end with that request. This ExportingReader has no timer of its own. shutdown() collects and attempts one synchronous export, in delta temporality. It is not a cumulative count across PHP requests. Pinned PHP ExportingReader
On FastCGI, Laravel can run termination work after sending the response. The worker still remains occupied while exporting. This demonstration uses a 250 ms HTTP client timeout and disables exporter retries. At higher traffic, measure worker occupancy with a healthy and unavailable destination. A nearby Collector can batch downstream writes, while the request-scoped PHP example still sends once per request. The example does not guarantee delivery.
A long-running queue worker can keep a provider across jobs. Keep the reader and call $reader->collect() on the worker's schedule. Call $provider->shutdown() once on graceful exit. Gauge readings such as queue depth belong with a component that sees the actual shared state. Incrementing and decrementing an UpDownCounter inside isolated requests does not give you concurrency across the PHP-FPM pool.
For a pull-based /metrics endpoint, use the separate PHP and Prometheus guide (Simplified Chinese). For instrument types and aggregation, see OpenTelemetry metrics.
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan
