使用 Prometheus 监控 PHP 应用程序:promphp/prometheus_client_php 库

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

PHP 中的 Prometheus 指标:promphp/prometheus_client_php 库完整指南



Prometheus 是现代 DevOps 基础设施中指标收集的事实标准。如果您的后端应用程序是用 PHP 编写的,您需要一个能够以 Prometheus 服务器可理解的格式导出指标的工具。promphp/prometheus_client_php 库是解决此问题最成熟且维护最完善的方案。在本文中,我们将介绍如何安装该库、创建基本指标(计数器、直方图、Summary)并将其暴露在 /metrics 端点。



什么是 promphp/prometheus_client_php?



这是由 promphp 社区开发的官方 Prometheus PHP 客户端。该库支持:

  • 四种主要指标类型:Counter(计数器)、Gauge(测量仪)、Histogram(直方图)、Summary(分位数)。
  • 存储适配器:内存(用于测试)、Redis、APCu 或文件系统。
  • 以 Prometheus 文本格式(text/plain)格式化输出。
  • 支持标签(labels)以实现多维数据。


安装



通过 Composer 进行安装。在项目根目录打开终端并执行:

composer require promphp/prometheus_client_php


安装后,在您的 PHP 脚本中引入 Composer 的自动加载器:

require __DIR__ . '/vendor/autoload.php';


创建指标注册表和存储适配器



第一步是创建一个 Registry(注册表)对象,用于存储所有指标,并选择一个存储适配器。为简单起见,我们使用内存适配器(数据仅在单个请求的生命周期内有效)。对于生产环境,通常使用 Redis 或 APCu。



use Prometheus\\CollectorRegistry;use Prometheus\\Storage\\InMemory;

$registry = new CollectorRegistry(new InMemory());


示例 1:Counter — 统计请求数量



计数器(Counter)是一个单调递增的值。非常适合统计 HTTP 请求、错误、数据库访问次数。



// 获取或创建计数器$counter = $registry->getOrRegisterCounter(    'my_app',           // 命名空间    'http_requests_total', // 指标名称    'Total number of HTTP requests', // 帮助描述    ['method', 'endpoint'] // 标签(labels));

// 使用特定标签递增计数器$counter->incBy(1, ['GET', '/api/users']);


在 /metrics 输出中,它将如下所示:

# HELP my_app_http_requests_total Total number of HTTP requests# TYPE my_app_http_requests_total countermy_app_http_requests_total{method="GET",endpoint="/api/users"} 1


示例 2:Gauge — 当前值(内存、连接数)



Gauge 既可以增加也可以减少。用于跟踪当前状态:活跃连接数、已用内存、任务队列。



use Prometheus\\Gauge;

$gauge = $registry->getOrRegisterGauge( 'my_app', 'memory_usage_bytes', 'Current memory usage in bytes', ['pool']);

// 设置值$gauge->set(memory_get_usage(true), ['main']);// 或者相对于当前值进行更改$gauge->inc(1024, ['main']); // +1KB$gauge->dec(512, ['main']); // -512B


示例 3:Histogram — 值分布(响应时间)



直方图将观测值分组到指定的桶(buckets)中。非常适合测量请求执行时间或响应大小。



use Prometheus\\Histogram;

$histogram = $registry->getOrRegisterHistogram( 'my_app', 'http_request_duration_seconds', 'Duration of HTTP requests in seconds', ['method', 'endpoint'], [0.1, 0.5, 1.0, 2.0, 5.0] // 桶(buckets)

推荐