l3tum/prometheus-metrics-bundle

Symfony 4/5 Prometheus Metrics Bundle

Installs: 1 632

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 1

Forks: 29

Type:symfony-bundle

1.9.0 2021-02-18 15:18 UTC

README

Master Develop
Build Status Build Status
[Coverage Status] [Coverage Status]

Symfony 5 Prometheus Metrics Bundle

Installation

Applications that use Symfony Flex

Open a command console, enter your project directory and execute:

$ composer require l3tum/prometheus-metrics-bundle

Applications that don't use Symfony Flex

Step 1: Download the Bundle

Open a command console, enter your project directory and execute the following command to download the latest stable version of this bundle:

$ composer require l3tum/prometheus-metrics-bundle

This command requires you to have Composer installed globally, as explained in the installation chapter of the Composer documentation.

Step 2: Enable the Bundle

Then, enable the bundle by adding it to the list of registered bundles in the app/AppKernel.php file of your project:

<?php
// app/AppKernel.php

// ...
class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            // ...
            new L3tum\PrometheusMetricsBundle\L3tumPrometheusMetricsBundle(),
        );

        // ...
    }

    // ...
}

Configuration

config.yaml

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

    # metrics backend type
    type: in_memory # possible values: in_memory, apcu, redis

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

    # used in case of type = "redis"
    redis:
        host: 127.0.0.1
        port: 6379
        timeout: 0.1
        read_timeout: 10
        persistent_connections: false
        password: ~

routes.yaml

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

You can alternatively define your own path and rules:

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

Now your metrics are available to Prometheus using http://<yourapp_url>/metrics/prometheus.

Custom Metrics Collector

If you want to collect your own metrics, you should create a class that will implement L3tum\PrometheusMetricsBundle\Metrics\MetricsCollectorInterface. Something like this:

<?php

declare(strict_types=1);

namespace App\Metrics;

use L3tum\PrometheusMetricsBundle\Metrics\MetricsCollectorInterface;
use Prometheus\CollectorRegistry;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Event\TerminateEvent;

/**
 * Class MyMetricsCollector.
 */
class MyMetricsCollector implements MetricsCollectorInterface
{
    /**
     * @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);
    }
}

When using autoconfigure = true, by implementing L3tum\PrometheusMetricsBundle\Metrics\MetricsCollectorInterface Symfony will automatically configure your metrics collector to be used by the collector registry.

If you don't use autoconfigure = true, then you will have to add this to your services.yaml:

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

Default Metrics

These are default metrics exported by the application:

# 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

Note that, php_info comes from the underlying library promphp/prometheus_client_php. Other metrics are gathered by the built-in class L3tum\PrometheusMetricsBundle\Metrics. Here, in the example we have a prefix symfony and the metrics show a single request to the root named app_dummy_homepage. Symfony instance is named dev here. Instance name comes from the server var HOSTNAME ($request->server->get('HOSTNAME')) and defaults to dev.

Code license

You are free to use the code in this repository under the terms of the MIT license. LICENSE contains a copy of this license.