mmo / guzzle-metrics-middleware
Package info
github.com/morawskim/guzzle-metrics-middleware
pkg:composer/mmo/guzzle-metrics-middleware
Requires
- php: >=8.3.0
- guzzlehttp/guzzle: ^7.0
Requires (Dev)
- phpunit/phpunit: ^12.0
- promphp/prometheus_client_php: ^2.15
This package is auto-updated.
Last update: 2026-07-11 17:00:35 UTC
README
A Guzzle HTTP client middleware that measures the duration of requests and collects metrics. It helps in monitoring external service calls by tracking request execution time, HTTP methods, target URIs, and response status codes.
Features
- Duration Tracking: Measures the time elapsed for each request (in milliseconds).
- Metric Abstraction: Decoupled from specific monitoring systems through the
DurationMetricCollectorInterface. - Prometheus Support: Includes a collector for Prometheus (using
promphp/prometheus_client_php). - Path Normalization: Supports URI path templates to prevent high cardinality in metrics (e.g., grouping
/users/1and/users/2under/users/<id>).
Installation
composer require mmo/guzzle-metrics-middleware
Usage
1. Initialize the Collector
You need a collector that implements DurationMetricCollectorInterface.
Prometheus
For Prometheus, you can use PrometheusHistogramDurationMetricCollector.
use Mmo\GuzzleMetricsMiddleware\Metric\Duration\PrometheusHistogramDurationMetricCollector; use Prometheus\CollectorRegistry; /** @var CollectorRegistry $registry */ $histogram = $registry->getOrRegisterHistogram( 'myapp', 'request_duration_ms', 'Guzzle request duration', ['method', 'uri', 'status_code'] ); $collector = new PrometheusHistogramDurationMetricCollector($histogram);
2. Set up the Middleware
Create the middleware and push it onto the Guzzle handler stack.
use GuzzleHttp\Client; use GuzzleHttp\HandlerStack; use Mmo\GuzzleMetricsMiddleware\DurationMetricMiddleware; $middleware = new DurationMetricMiddleware($collector); $stack = HandlerStack::create(); $stack->push($middleware); $client = new Client(['handler' => $stack]);
3. Path Templating (Optional)
To avoid creating a separate metric for every unique URL (which can lead to performance issues in monitoring systems), you can provide a template for the URI path using the DurationMetricMiddleware::URI_PATH_TEMPLATE option.
$client->request('GET', '/users/123', [ DurationMetricMiddleware::URI_PATH_TEMPLATE => '/users/<id>' ]);
The metric will then use example.com/users/<id> instead of example.com/users/123.
Relative vs Absolute Templates
- Relative templates: If you use a
base_uriin Guzzle, a relative template will be appended to it. - Absolute templates: Starting with a
/will replace the path portion of the URI in the metrics.
License
MIT