Prometheus PHP 客户端库使用教程
项目介绍
prometheus_client_php
是一个用于 PHP 应用程序的 Prometheus 监控指标库。Prometheus 是一个开源的系统监控和警报工具包,而 prometheus_client_php
允许 PHP 开发者轻松地集成 Prometheus 监控到他们的应用中。
项目快速启动
安装
首先,通过 Composer 安装 prometheus_client_php
:
composer require promphp/prometheus_client_php
基本使用
以下是一个简单的示例,展示如何在 PHP 应用中收集和暴露 Prometheus 指标:
<?php
require 'vendor/autoload.php';
use Prometheus\CollectorRegistry;
use Prometheus\RenderTextFormat;
use Prometheus\Storage\InMemory;
$registry = new CollectorRegistry(new InMemory());
$counter = $registry->registerCounter('test', 'some_counter', 'it increases', ['type']);
$counter->incBy(3, ['blue']);
$renderer = new RenderTextFormat();
$result = $renderer->render($registry->getMetricFamilySamples());
header('Content-type: ' . RenderTextFormat::MIME_TYPE);
echo $result;
应用案例和最佳实践
应用案例
假设你有一个 Web 应用,你希望监控每个 HTTP 请求的处理时间。你可以使用 prometheus_client_php
来收集这些指标:
<?php
require 'vendor/autoload.php';
use Prometheus\CollectorRegistry;
use Prometheus\Storage\InMemory;
$registry = new CollectorRegistry(new InMemory());
$histogram = $registry->registerHistogram('app', 'response_time_seconds', 'response time', [], [0.1, 0.2, 0.5, 1, 2, 5]);
$start = microtime(true);
// 处理请求
$duration = microtime(true) - $start;
$histogram->observe($duration);
最佳实践
- 命名规范:遵循 Prometheus 的命名规范,使用下划线分隔单词,避免使用大写字母。
- 标签使用:合理使用标签,避免过多的标签组合导致维度爆炸。
- 持久化存储:在生产环境中,考虑使用持久化存储(如 Redis)来存储指标数据。
典型生态项目
Prometheus Push Gateway
prometheus_push_gateway_php
是一个用于 PHP 应用的 Prometheus Push Gateway 客户端库。它允许你将指标推送到 Push Gateway,特别适用于短生命周期的任务或无法直接暴露指标的服务。
安装
composer require promphp/prometheus_push_gateway_php
使用示例
<?php
require 'vendor/autoload.php';
use Prometheus\CollectorRegistry;
use Prometheus\PushGateway\PushGateway;
use Prometheus\Storage\InMemory;
$registry = new CollectorRegistry(new InMemory());
$counter = $registry->registerCounter('test', 'some_counter', 'it increases', ['type']);
$counter->incBy(3, ['blue']);
$pushGateway = new PushGateway('http://127.0.0.1:9091');
$pushGateway->push($registry, 'my_job', ['instance' => 'foo']);
通过这些模块的介绍和示例,你应该能够快速上手并集成 prometheus_client_php
到你的 PHP 应用中,实现高效的监控和指标收集。