PHPackages                             alexpon92/php2elk-metrics - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Search &amp; Filtering](/categories/search)
4. /
5. alexpon92/php2elk-metrics

ActiveLibrary[Search &amp; Filtering](/categories/search)

alexpon92/php2elk-metrics
=========================

Package to transfer application and monitoring metrics to ELK

1.4.1(2y ago)023.9k↓100%MITPHPPHP &gt;=7.1CI failing

Since Apr 28Pushed 2y ago2 watchersCompare

[ Source](https://github.com/alexpon92/php2elk-metrics)[ Packagist](https://packagist.org/packages/alexpon92/php2elk-metrics)[ RSS](/packages/alexpon92-php2elk-metrics/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (9)Dependencies (4)Versions (14)Used By (0)

PHP2ELK Metrics Package
=======================

[](#php2elk-metrics-package)

- [Overview](#overview)
- [Installation](#getting-started)
- [Configuration](#configuratuion)
- [Usage](#usage)
- [Index and default mappings creation](#index-creation)
- [Check mappings](#check-mappings)
- [Non Laravel users](#not-laravel-users)

Overview
--------

[](#overview)

This package helps to transfer application metrics to elasticsearch to some indices with prepared mappings for metrics fields. Using Kibana on top of elastic gives you an opportunity to create informative dashboards or trigger some monitoring events. You can use it with Laravel applications or with other frameworks. This package is based on official elasticsearch client ().

Installation
------------

[](#installation)

To install through composer, run the following command from terminal:

```
composer require alexpon92/php2elk-metrics
```

Configuration
-------------

[](#configuration)

Register the main package provider in your applications

```
Php2ElkMetrics\Laravel\Providers\Php2ElkMetricsProvider::class
```

It gives you an opportunity to publish default config and edit it:

```
php artisan vendor:publish --provider="Php2ElkMetrics\Laravel\Providers\Php2ElkMetricsProvider" --tag=config
```

Also, you may publish another provider to register main package services in your service container:

```
php artisan vendor:publish --provider="Php2ElkMetrics\Laravel\Providers\Php2ElkMetricsProvider" --tag=service-provider
```

It will place package service provider in your `App\Providers` directory.

Usage
-----

[](#usage)

- Create your custom metrics package has `BaseMetric` class, and all of your metrics must extend this base class.
- Implement necessary methods:

```
    /**
     * Unique metric name
     * @return string
     */
    abstract public static function getName(): string;

    /**
     * Method to convert metric contents to array
     *
     * @return array
     */
    abstract public function arraySerialize(): array;
```

`getName` method provides unique metric name.

`arraySerialize` method helps to serialize metric fields to associative array.

Example of custom metric:

```
namespace App\Metrics;

use Php2ElkMetrics\Metrics\BaseMetric;
use DateTime;

class SomeVisitDurationMetric extends BaseMetric
{
    /**
     * @var string
     */
    private $userName;

    /**
     * @var float
     */
    private $duration;

    /**
     * SomeVisitDurationMetric constructor.
     *
     * @param string        $userName
     * @param float         $duration
     * @param DateTime|null $time
     */
    public function __construct(string $userName, float $duration, ?DateTime $time)
    {
        $this->userName = $userName;
        $this->duration = $duration;
        $this->time     = $time; // time is protected field from BaseMetric class
    }

    public static function getName(): string
    {
        return 'some_duration_metric';
    }

    public function arraySerialize(): array
    {
        return [
            'user_name' => $this->userName,
            'duration'  => $this->duration
        ];
    }
}
```

- Add your new metrics to metrics registry

If you have published default package provider with command:

```
php artisan vendor:publish --provider="Php2ElkMetrics\Laravel\Providers\Php2ElkMetricsProvider" --tag=service-provider
```

You should edit it and add your new metric in register method:

```
    $this->app->singleton(
        Registry::class,
        static function ($app) {
            /** @var Container $app */
            $metricRegistry = new Registry();

            $defaultIndex = config('php2elk-metrics.default_index');
            $defaultConnection = config('php2elk-metrics.connections.default');

            $metricRegistry->add(
                new MetricsConfig(
                    SomeVisitDurationMetric::getName(),
                    $defaultIndex,
                    $defaultConnection
                )
            );

            return $metricRegistry;
        }
    );
```

- Add metric mappings in elasticsearch for your index, for instance in kibana dev console:

```
PUT /_mappings
{
  "properties": {
    "some_duration_metric": {
      "properties": {
        "user_name": {
          "type": "keyword"
        },
        "duration": {
          "type": "float"
        }
      }
    }
  }
}

```

**IMPORTANT!**If you will not add mapping for new metrics and produce metrics from your application, your new fields will be converted to strings by elastics and you can't use it in aggregations etc., only for concrete search. Only reindex may help in this situation.

- Now you can produce it in your application

```
$producer = app(\Php2ElkMetrics\MetricsProducer\MetricsProducer::class);
$metric = new SomeVisitDurationMetric('John', 12.02);
$producer->produceMetric($metric);
```

After publish, document in elastic will have next structure:

```
{
  "application": "some-app", //may be changed in config
  "instance": "test-instance", //may be changed in config
  "timestamp": 1587735900, //time which is passed in metrics constructor
  "metric_name": "some_duration_metric", //unique metric key, to be able to filter it in elastic index
  "some_duration_metric": { //metric object content
    "user_name": "John",
    "count": 15.02
 }

```

- Asynch Metrics producing Package has default listener to produce metric in asynch mode to prevent any additional delays. To use it, you should register `Php2ElkMetrics\Laravel\Listeners\MetricsEventListener`in your `App\Providers\EventServiceProvider` in `protected $subscribe` attribute

```
$metric = new SomeVisitDurationMetric('John', 12.02);
event(new \Php2ElkMetrics\Events\MetricEvent($metric, new \DateTime()));
```

- Bulk metrics producing

```
$producer = app(\Php2ElkMetrics\MetricsProducer\MetricsProducer::class);
$metricsCollection = new \Php2ElkMetrics\Metrics\MetricsCollection();
$metricsCollection
    ->add(new SomeVisitDurationMetric('John', 12.02))
    ->add(new SomeVisitDurationMetric('Alex', 30.02));
$producer->bulkProduce($metricsCollection);
```

### Create Index and default mappings

[](#create-index-and-default-mappings)

Package has artisan command to prepare an index for your metrics:

```
php artisan php2elk:setup-index {--connection_name=} {--index_name=} {--default_metrics}
```

`--connection_name` - to specify connection name from your config (or default connection) `--index_name` - index name (or default index from config if not passed) `--default_metrics` - flag to add default package metrics

Package has some default metrics and collectors:

- Dead rows collector for PostgreSQL `\Php2ElkMetrics\Laravel\Collectors\Postgres\DeadRowsMetricsCollector`This collector estimates number of dead rows in concrete database and produce `Php2ElkMetrics\Metrics\DefaultMetrics\Postgres\TableDeadRowsMetric`Also you can use artisan command to launch collection of this metric it in crontab

```
php artisan php2elk:php2elk:collect-postgres-dead-rows
```

- Failed queue jobs collector `\Php2ElkMetrics\Laravel\Collectors\FailedQueues\FailedQueuesMetricsCollector`This collector estimates number of failed jobs and produce `\Php2ElkMetrics\Laravel\DefaultMetrics\FailedQueue\FailedQueueJobsMetric`Also you can use artisan command to launch collection of this metric it in crontab

```
php artisan php2elk:php2elk:php2elk:collect-failed-queues
```

- Latency metric `\Php2ElkMetrics\Metrics\BaseMetric\LatencyMetric`This metric helps to estimate latency of some actions in your application.

Check mappings
--------------

[](#check-mappings)

To check metrics mappings in elasticsearch package has command

```
php artisan php2elk:check-mappings
```

It helps you not to corrupt your index and to check new metrics mappings in elasticsearch before deploy of new version.

Non Laravel users
-----------------

[](#non-laravel-users)

WIP

###  Health Score

30

—

LowBetter than 64% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity22

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity57

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 85.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~106 days

Recently: every ~290 days

Total

12

Last Release

1038d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/c28b8eaa859f3186d14291d43851d0f9aea0c9b8a0df06bc4a5cd193eba96b48?d=identicon)[alexpon92](/maintainers/alexpon92)

---

Top Contributors

[![alexpon92](https://avatars.githubusercontent.com/u/16165027?v=4)](https://github.com/alexpon92 "alexpon92 (18 commits)")[![masunov](https://avatars.githubusercontent.com/u/1958751?v=4)](https://github.com/masunov "masunov (2 commits)")[![osavchenko](https://avatars.githubusercontent.com/u/617002?v=4)](https://github.com/osavchenko "osavchenko (1 commits)")

---

Tags

phpelasticsearchMetricsELK

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/alexpon92-php2elk-metrics/health.svg)

```
[![Health](https://phpackages.com/badges/alexpon92-php2elk-metrics/health.svg)](https://phpackages.com/packages/alexpon92-php2elk-metrics)
```

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
