ns3777k / prometheus-bundle
Symfony 扩展包,用于收集和暴露 Prometheus 指标
v1.0.2
2020-03-11 22:57 UTC
Requires
- php: ^7.1
- endclothing/prometheus_client_php: ^1.0
- symfony/config: ^4.3.0|^5.0.0
- symfony/dependency-injection: ^4.3.0|^5.0.0
- symfony/http-kernel: ^4.3.0|^5.0.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.16
- phpunit/phpunit: ^9.0
Suggests
- ext-apcu: Required if using APCu as prometheus metrics backend
- ext-redis: Required if using Redis as prometheus metrics backend
This package is auto-updated.
Last update: 2024-09-12 08:54:03 UTC
README
要求
- PHP 7.3+
- Symfony 4+
安装
安装此扩展包有两种方式:使用 flex 自动安装或手动安装。
使用 symfony flex
$ composer require ns3777k/prometheus-bundle
手动
- 需要此包
$ composer require ns3777k/prometheus-bundle
- 在
config/bundles.php
中注册扩展包
<?php return [ // ... Ns3777k\PrometheusBundle\Ns3777kPrometheusBundle::class => ['all' => true], ];
- 配置(见下文)
使用
配置
config/packages/ns3777k_prometheus.yaml
:
ns3777k_prometheus: namespace: app adapter: in_memory # or apcu or redis # listener (read below) listener: enabled: true ignored_routes: [] # redis adapter settings redis: host: '127.0.0.1' port: 6379 timeout: 0.1 read_timeout: 10 persistent_connections: false password: database:
要注册指标路由,请将以下内容添加到 config/routes.yaml
metrics: path: /metrics controller: 'Ns3777k\PrometheusBundle\Controller\MetricsController::prometheus'
或
metrics: resource: '@Ns3777kPrometheusBundle/Resources/config/routing.xml'
内置监听器
默认情况下,监听器处于开启状态,并仅收集一个请求持续时间(以秒为单位,request_duration_seconds
)的直方图,包含3个标签:code
、method
和 route
。
直方图会自动创建 total
和 count
指标。
通常,您不想收集类似于 _wdt
和 metrics
(这是 /metrics
路由)的路由的指标,这时就需要使用 listener.ignored_routes
。
监听器的常见 PromQL 查询
- HTTP 请求速率
rate(request_duration_seconds_sum[5m]) / rate(request_duration_seconds_count[5m])
- HTTP 成功响应
request_duration_seconds_count{code=~"(2|3).*"}
- HTTP 失败响应
request_duration_seconds_count{code=~"(4|5).*"}
- HTTP 成功响应时间 5m 95p
histogram_quantile(0.95, rate(request_duration_seconds_bucket{code=~"(2|3).*"}[5m]))
收集自己的指标
内置监听器仅涵盖请求和响应的基本信息。您可以使用它来获取前10个请求、慢速响应、计算请求速率等。
但大多数情况下,您需要收集自己的指标。使用 CollectorRegistryInterface
(由 NamespacedCollectorRegistry
实现)很容易做到。
直方图示例
<?php declare(strict_types=1); namespace App\Weather; use Ns3777k\PrometheusBundle\Metrics\CollectorRegistryInterface; class WeatherClient { private $registry; public function __construct(CollectorRegistryInterface $registry) { $this->registry = $registry; } public function getWeatherForRegion(string $region) { $histogram = $this->registry->getOrRegisterHistogram( 'weather_request_duration_seconds', 'Weather request duration with response information', ['region'] ); $start = microtime(true); // do request $duration = microtime(true) - $start; $histogram->observe($duration, [$region]); } }
不用担心命名空间。它将自动从扩展包的配置中添加前缀。
安全性
请记住,当您添加 /metrics
路由时,它将公开对互联网可用。
您需要限制对其的访问(例如使用 nginx)。