artprima/prometheus-metrics-bundle

Symfony 5 / 6 Prometheus Metrics Bundle

安装次数: 2,070,038

依赖关系: 2

建议者: 0

安全: 0

星标: 126

关注者: 9

分支: 29

开放问题: 2

类型:symfony-bundle

1.19.0 2023-12-04 12:39 UTC

This package is auto-updated.

Last update: 2024-08-31 00:35:33 UTC


README

Symfony 5/6/7 Prometheus Metrics Bundle

promphp/prometheus_client_php 提供的 Symfony 扩展包。

安装

使用 Symfony Flex 的应用程序

打开命令行,进入您的项目目录并执行

composer require artprima/prometheus-metrics-bundle

不使用 Symfony Flex 的应用程序

步骤 1: 下载 Bundle

打开命令行,进入您的项目目录并执行以下命令以下载此 Bundle 的最新稳定版本

composer require artprima/prometheus-metrics-bundle

此命令要求您全局安装 Composer,请参阅 Composer 文档中的安装章节

步骤 2: 启用 Bundle

然后,通过将其添加到项目中 app/AppKernel.php 文件中注册的 Bundle 列表来启用 Bundle

<?php
// app/AppKernel.php

// ...
class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = [
            // ...
            new Artprima\PrometheusMetricsBundle\ArtprimaPrometheusMetricsBundle(),
        ];

        // ...
    }

    // ...
}

配置

config.yaml

artprima_prometheus_metrics:
    # namespace is used to prefix the prometheus metrics
    namespace: myapp

    # ignoring some routes in metrics
    ignored_routes: [some_route_name, another_route_name]

    # metrics backend
    storage:
        # DSN of the storage. All parsed values will override explicitly set parameters. Ex: redis://127.0.0.1?timeout=0.1
        url: ~
        
        # Known values: in_memory, apcu, apcng, redis
        type: in_memory
        
        # Available parameters used by redis
        host: 127.0.0.1
        port: 6379
        timeout: 0.1
        read_timeout: 10
        persistent_connections: false
        password: ~
        database: ~ # Int value used by redis adapter
        prefix: ~   # String value used by redis and apcu

        # A variable parameter to define additionnal options as key / value.
        options:
            foo: bar

    # used to disable default application metrics
    disable_default_metrics: false

    # used to disable default metrics from promphp/prometheus_client_php
    disable_default_promphp_metrics: false

    # used to enable console metrics
    enable_console_metrics: false

支持类型包括

routes.yaml

# expose /metrics/prometheus in your application
app_metrics:
    resource: '@ArtprimaPrometheusMetricsBundle/Resources/config/routing.xml'

您也可以定义自己的路径和规则

app_metrics:
    path: /mypath/mymetrics
    controller: Artprima\PrometheusMetricsBundle\Controller\MetricsController::prometheus

现在您的指标可通过 http://<yourapp_url>/metrics/prometheus 使用 Prometheus 访问。

自定义指标收集器

如果您想收集自己的指标,应创建一个类来实现一个或多个继承自 Artprima\PrometheusMetricsBundle\Metrics\MetricsCollectorInterface 的接口。

<?php

declare(strict_types=1);

namespace App\Metrics;

use Artprima\PrometheusMetricsBundle\Metrics\RequestMetricsCollectorInterface;
use Artprima\PrometheusMetricsBundle\Metrics\TerminateMetricsCollectorInterface;
use Prometheus\CollectorRegistry;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Event\TerminateEvent;

/**
 * Class MyMetricsCollector.
 */
class MyMetricsCollector implements RequestMetricsCollectorInterface, TerminateMetricsCollectorInterface
{
    /**
     * @var string
     */
    private $namespace;

    /**
     * @var CollectorRegistry
     */
    private $collectionRegistry;

    public function init(string $namespace, CollectorRegistry $collectionRegistry): void
    {
        $this->namespace = $namespace;
        $this->collectionRegistry = $collectionRegistry;
    }

    private function incRequestsTotal(?string $method = null, ?string $route = null): void
    {
        $counter = $this->collectionRegistry->getOrRegisterCounter(
            $this->namespace,
            'http_requests_total',
            'total request count',
            ['action']
        );

        $counter->inc(['all']);

        if (null !== $method && null !== $route) {
            $counter->inc([sprintf('%s-%s', $method, $route)]);
        }
    }

    private function incResponsesTotal(?string $method = null, ?string $route = null): void
    {
        $counter = $this->collectionRegistry->getOrRegisterCounter(
            $this->namespace,
            'http_responses_total',
            'total response count',
            ['action']
        );
        $counter->inc(['all']);

        if (null !== $method && null !== $route) {
            $counter->inc([sprintf('%s-%s', $method, $route)]);
        }
    }

    // called on the `kernel.request` event
    public function collectRequest(RequestEvent $event): void
    {
        $request = $event->getRequest();
        $requestMethod = $request->getMethod();
        $requestRoute = $request->attributes->get('_route');

        // do not track "OPTIONS" requests
        if ('OPTIONS' === $requestMethod) {
            return;
        }

        $this->incRequestsTotal($requestMethod, $requestRoute);
    }

    // called on the `kernel.terminate` event
    public function collectResponse(TerminateEvent $event): void
    {
        $response = $event->getResponse();
        $request = $event->getRequest();

        $requestMethod = $request->getMethod();
        $requestRoute = $request->attributes->get('_route');

        $this->incResponsesTotal($requestMethod, $requestRoute);
    }
}

当使用 autoconfigure = true 时,通过实现 Artprima\PrometheusMetricsBundle\Metrics\MetricsCollectorInterface,Symfony 将自动配置您的指标收集器以供收集器注册器使用。

通过实现以下接口之一,您可以在列表中列出的 Symfony 内核事件上收集指标

  • Artprima\PrometheusMetricsBundle\Metrics\PreRequestMetricsCollectorInterface
    • 在 "kernel.request" 事件上收集指标,优先级为 1024。
  • Artprima\PrometheusMetricsBundle\Metrics\RequestMetricsCollectorInterface
    • 在 "kernel.request" 事件上收集指标(默认优先级)。
  • Artprima\PrometheusMetricsBundle\Metrics\PreExceptionMetricsCollectorInterface
    • 在 "kernel.exception" 事件上收集指标,优先级为 1024。
  • Artprima\PrometheusMetricsBundle\Metrics\ExceptionMetricsCollectorInterface
    • 在 "kernel.exception" 事件上收集指标(默认优先级)。
  • Artprima\PrometheusMetricsBundle\Metrics\TerminateMetricsCollectorInterface
    • 在 "kernel.terminate" 事件上收集指标。

以下收集器只有在您在 Bundle 配置中定义 enable_console_metrics: true 时才会工作

  • Artprima\PrometheusMetricsBundle\Metrics\ConsoleCommandMetricsCollectorInterface
    • 在 "console.command" 事件上收集指标。
  • Artprima\PrometheusMetricsBundle\Metrics\ConsoleTerminateMetricsCollectorInterface
    • 在 "console.terminate" 事件上收集指标。
  • Artprima\PrometheusMetricsBundle\Metrics\ConsoleErrorMetricsCollectorInterface
    • 在 "console.error" 事件上收集指标。

对于高级使用,您可以直接实现 Artprima\PrometheusMetricsBundle\Metrics\MetricsCollectorInterface

还有 Artprima\PrometheusMetricsBundle\Metrics\MetricsCollectorInitTrait 会使您的收集器具有 init 方法。

如果您未使用 autoconfigure = true,那么您将需要将其添加到您的 services.yaml

    App\Metrics\MyMetricsCollector:
        tags:
            - { name: prometheus_metrics_bundle.metrics_generator }

自定义存储适配器工厂

存储适配器是 Prometheus\Storage\Adapter 的一个实例。要创建自己的存储适配器,您应创建一个自定义工厂,实现 Artprima\PrometheusMetricsBundle\StorageFactory\StorageFactoryInterface

<?php

declare(strict_types=1);

namespace App\Metrics;

use Artprima\PrometheusMetricsBundle\StorageFactory\StorageFactoryInterface;
use Prometheus\Storage\Adapter;

class DummyFactory implements StorageFactoryInterface
{
    public function getName(): string
    {
        return 'dummy';
    }

    public function create(array $options): Adapter
    {
        return new Dummy($options);
    }
}

Symfony 将自动配置您的存储工厂,前提是使用 autoconfigure = true 并实现 Artprima\PrometheusMetricsBundle\StorageFactory\StorageFactoryInterface。如果您未使用 autoconfigure = true,那么您将需要将其添加到您的 services.yaml

    App\Metrics\DummyFactory:
        tags:
            - { name: prometheus_metrics_bundle.adapter_factory }

默认指标

这些是应用程序导出的默认指标

# TYPE php_info gauge
php_info{version="7.3.25-1+ubuntu18.04.1+deb.sury.org+1"} 1
# HELP symfony_http_2xx_responses_total total 2xx response count
# TYPE symfony_http_2xx_responses_total counter
symfony_http_2xx_responses_total{action="GET-app_dummy_homepage"} 1
symfony_http_2xx_responses_total{action="all"} 1
# HELP symfony_http_requests_total total request count
# TYPE symfony_http_requests_total counter
symfony_http_requests_total{action="GET-app_dummy_homepage"} 1
symfony_http_requests_total{action="all"} 1
# HELP symfony_instance_name app instance name
# TYPE symfony_instance_name gauge
symfony_instance_name{instance="dev"} 1

请注意,php_info来自底层库promphp/prometheus_client_php。其他指标是通过内置类Artprima\PrometheusMetricsBundle\Metrics收集的。在此示例中,我们有一个前缀symfony,指标显示了一个名为app_dummy_homepage的根请求。在此处,Symfony实例名为dev。实例名称来自服务器变量HOSTNAME$request->server->get('HOSTNAME')),默认为dev

清除指标

该包提供了一个控制台命令来清除存储中的指标。只需运行

./bin/console artprima:prometheus:metrics:clear

贡献者

代码许可

您可以在MIT许可的条款下自由使用此存储库中的代码。LICENSE文件包含了此许可证的副本。