Prometheus metrics for PHP workers via RoadRunner RPC
PHP client for the RoadRunner metrics plugin. It lets application workers declare Prometheus collectors and publish values to them over RPC.
composer require spiral/roadrunner-metricsThe package requires PHP 8.2+ and RoadRunner v3. You can use the convenient installer to download the latest available compatible version of RoadRunner assembly:
composer require spiral/roadrunner-cli --dev
vendor/bin/rr getEnable metrics service in your .rr.yaml file:
rpc:
listen: tcp://127.0.0.1:6001
server:
command: "php worker.php"
http:
address: "0.0.0.0:8080"
metrics:
address: "0.0.0.0:2112"See the metrics plugin documentation for all options.
To publish metrics from your application worker:
<?php
declare(strict_types=1);
use Nyholm\Psr7\Factory\Psr17Factory;
use Nyholm\Psr7\Response;
use Spiral\Goridge\RPC\RPC;
use Spiral\RoadRunner;
use Spiral\RoadRunner\Metrics\Collector;
use Spiral\RoadRunner\Metrics\Metrics;
include 'vendor/autoload.php';
$factory = new Psr17Factory();
$worker = new RoadRunner\Http\PSR7Worker(RoadRunner\Worker::create(), $factory, $factory, $factory);
# Create metrics client
$metrics = new Metrics(
RPC::create(RoadRunner\Environment::fromGlobals()->getRPCAddress()),
);
# Declare counter
$metrics->declare(
'http_requests',
Collector::counter()
->withHelp('Collected HTTP requests.')
->withLabels('status', 'method'),
);
while ($request = $worker->waitRequest()) {
try {
$response = new Response();
$response->getBody()->write('hello world');
# Publish metrics for each request with labels (status, method)
$metrics->add('http_requests', 1, [
(string) $response->getStatusCode(),
$request->getMethod(),
]);
$worker->respond($response);
} catch (\Throwable $e) {
$worker->getWorker()->error((string) $e);
$metrics->add('http_requests', 1, ['503', $request->getMethod()]);
}
}Collectors are created with Collector::counter(), Collector::gauge(), Collector::histogram(...$buckets) and
Collector::summary(); values are published with add(), sub(), set() and observe().
MetricsFactory wraps the client according to MetricsOptions: it retries failed calls (3 attempts by default),
can suppress and log exceptions, and can skip waiting for RPC responses when given an AsyncRPCInterface:
use Spiral\RoadRunner\Metrics\MetricsFactory;
use Spiral\RoadRunner\Metrics\MetricsOptions;
$metrics = MetricsFactory::createMetrics(
$rpc,
new MetricsOptions(
retryAttempts: 3,
retrySleepMicroseconds: 50,
suppressExceptions: true,
ignoreResponsesWherePossible: true,
),
$logger, // any PSR-3 logger
);