定制 mmo/guzzle-metrics-middleware 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

mmo/guzzle-metrics-middleware

Composer 安装命令:

composer require mmo/guzzle-metrics-middleware

包简介

README 文档

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/1 and /users/2 under /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_uri in 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

统计信息

  • 总下载量: 0
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 2
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-07-11

承接程序开发

PHP开发

VUE

Vue开发

前端开发

小程序开发

公众号开发

系统定制

数据库设计

云部署

网站建设

安全加固