Simple library that abstracts different metrics collectors. I find this necessary to have a consistent and simple metrics (functional) API that doesn't cause vendor lock-in.

Overview

Metrics

Build Status

Simple library that abstracts different metrics collectors. I find this necessary to have a consistent and simple metrics API that doesn't cause vendor lock-in.

It also ships with a Symfony Bundle. This is not a library for displaying metrics.

Currently supported backends:

  • Doctrine DBAL
  • Graphite
  • InfluxDB
  • Telegraf
  • Librato
  • Logger (Psr\Log\LoggerInterface)
  • Null (Dummy that does nothing)
  • Prometheus
  • StatsD
  • Zabbix
  • DogStatsD

Installation

Using Composer:

composer require beberlei/metrics

API

You can instantiate clients:

<?php

$collector = \Beberlei\Metrics\Factory::create('statsd');

You can measure stats:

<?php

$collector->increment('foo.bar');
$collector->decrement('foo.bar');

$start = microtime(true);
$diff  = microtime(true) - $start;
$collector->timing('foo.bar', $diff);

$value = 1234;
$collector->measure('foo.bar', $value);

Some backends defer sending and aggregate all information, make sure to call flush:

<?php

$collector->flush();

Configuration

<?php
$statsd = \Beberlei\Metrics\Factory::create('statsd');

$zabbix = \Beberlei\Metrics\Factory::create('zabbix', array(
    'hostname' => 'foo.beberlei.de',
    'server'   => 'localhost',
    'port'     => 10051,
));

$zabbixConfig = \Beberlei\Metrics\Factory::create('zabbix_file', array(
    'hostname' => 'foo.beberlei.de',
    'file'     => '/etc/zabbix/zabbix_agentd.conf'
));

$librato = \Beberlei\Metrics\Factory::create('librato', array(
    'hostname' => 'foo.beberlei.de',
    'username' => 'foo',
    'password' => 'bar',
));

$null = \Beberlei\Metrics\Factory::create('null');

Symfony Bundle Integration

Register Bundle into Kernel:

<?php

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        //..
        $bundles[] = new \Beberlei\Bundle\MetricsBundle\BeberleiMetricsBundle();
        //..
    }
}

Do Configuration:

# app/config/config.yml
beberlei_metrics:
    default: foo
    collectors:
        foo:
            type: statsd
        bar:
            type: zabbix
            prefix: foo.beberlei.de
            host: localhost
            port: 10051
        baz:
            type: zabbix_file
            prefix: foo.beberlei.de
            file: /etc/zabbix/zabbix_agentd.conf
        librato:
            type: librato
            username: foo
            password: bar
            source: hermes10
        dbal:
            type: doctrine_dbal
            connection: metrics # using the connection named "metrics"
        monolog:
            type: monolog
        influxdb:
            type: influxdb
            influxdb_client: influxdb_client_service # using the InfluxDB client service named "influxdb_client_service"
            tags:
                dc: "west"
                node_instance: "hermes10"
        prometheus:
            type: prometheus
            prometheus_collector_registry: prometheus_collector_registry_service # using the Prometheus collector registry service named "prometheus_collector_registry_service"
            namespace: app_name # optional
            tags:
                dc: "west"
                node_instance: "hermes10"

This adds collectors to the Metrics registry. The functions are automatically included in the Bundle class so that in your code you can just start using the convenient functions. Metrics are also added as services:

<?php

$metrics = $container->get('beberlei_metrics.collector.foo');

and the default collector can be fetched:

<?php

$metrics = $container->get('beberlei_metrics.collector');
Comments
  • Added support for tags in the StatsD collector

    Added support for tags in the StatsD collector

    I've seen that the tag support has currently been implemented only for the InfluxDB collector, so I'd like to try giving my contributon by adding it to the StatsD collector as well.

    opened by dsantang 9
  • Symfony 4 compatibility

    Symfony 4 compatibility

    When using this library in Symfony 4, you get the following error

    Fatal error: Uncaught Error: Class 'Symfony\Component\DependencyInjection\DefinitionDecorator'
    not found in vendor/beberlei/metrics/src/Beberlei/Bundle/MetricsBundle/DependencyInjection/BeberleiMetricsExtension.php
    on line 39
    

    In the Symfony 4.0 upgrade guide there is a note:

    The DefinitionDecorator class has been removed. Use the ChildDefinition class instead.
    

    Problem: The alternative (ChildDefinition) was introduced in Symfony 3.3, but this package appears to support earlier versions.

    So we should either up the minimal requirement to 3.3 (or 4.0?), or do some kind of class_exists hack. Preferences?

    opened by nicoschoenmaker 8
  • Add context logger

    Add context logger

    The context logger makes use of the context array replacement feature defined in PSR-3. See https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md#12-message for an example.

    If you use monolog you should add the PsrLogMessageProcessor to your logger to enable replacement of the variables.

    opened by davidfuhr 8
  • Add support for tagging metrics?

    Add support for tagging metrics?

    First, great library, I just thought about implementing something similar to prevent vendor lock-in. For now we will use datadog for our metric needs. StatsD (Datadog) supports adding arbitrary tags to metrics. Could that be added on the Collector API level with the default that other Collectors would not support tags? Or perhaps there are even more collectors that also support tags and could be enhanced to support tags. If we would make the parameter tags optional with an empty default value it would also be backwards compatible for all users of the library. Only the collectors would need to be modified to account for the new parameter. What do you think? (I would gladly implement this if there is a chance to include this, otherwise I will probably create my own fork)

    opened by Shyru 8
  • Why not flushing on destruct?

    Why not flushing on destruct?

    I was just looking at the library and it struck me odd why there is no destructor defined that would flush. Is that on purpose and if so whats the rationale behind it? If there is nothing against it I'd gladly add it in.

    opened by ChristianRiesen 7
  • Fixed statsd collector when stastd is down

    Fixed statsd collector when stastd is down

    Code to reproduce:

    <?php
    
    // Note: nothing listen on port 12345!!
    $fp = fsockopen("udp://localhost", 12345, $errno, $errstr, 1.0);
    var_dump($fp, $errno, $errstr); // Everything OK
    fwrite($fp, "1"); // OK
    fwrite($fp, "1"); // KO
    fclose($fp);
    
    echo "END";
    

    Note:

    No need to try catch, no exception can be trowed, and actually the code catch only Beberlei\Metrics\Exception which does not exist.

    opened by lyrixx 7
  • Minor code improvements

    Minor code improvements

    • [x] Use single quotes when possible
    • [x] Improve readability of string constructs
    • [ ] ~~Flags Graphite::push() as deprecated (shouldn't be part of the public interface)~~
    opened by eexit 6
  • Problem with flush during shutdown in symfony2

    Problem with flush during shutdown in symfony2

    Hello,

    I just have a problem with the defer sending feature with the librato backend.

    Let say I want to count a login event. So I put the $metric->increment('login'); code in the loginSuccess event. The controller then send the redirectResponse. The browser parse it and do the redirect and sadly I see that I am not yet logged.

    I have found that the redirect is made before the session has been written (register_shutdown_function) because of the librato post that take too much time. So I wonder what is the best practice in this case. I guess I have to post my metrics before the redirect is sent to the browser.

    What is your opinion on that ?

    opened by erichard 5
  • Allow Symfony 4 using class_exists

    Allow Symfony 4 using class_exists

    Fixes #58.

    The bare minimum needed to allow Symfony 4, in a backwards compatible way. Basically fixes the point where it crashes.

    Alternative, more proper fix can be found at #59.

    opened by nicoschoenmaker 4
  • Symfony 4 compat, require 3.3 or higher

    Symfony 4 compat, require 3.3 or higher

    Fixes #58.

    Currently the (Symfony) class DefinitionDecorator is used, which has been renamed to ChildDefinition.

    Problem at hand: this new class was only introduced in Symfony 3.3.

    This is the most clean, but also a bit of an aggressive solution to this problem: require Symfony 3.3 (or 4.0).

    • Use ChildDefinition over DefinitionDecorator
    • Symfony 4 makes services private by default, so had to make some of them public in unit-tests.
    • Was forced to use PHPUnit\Framework\TestCase over \PHPUnit_Framework_TestCase, since otherwise I was unable to install the later Symfony versions. This makes it compatible with PHPUnit 6, which is nice.
    • Dropped php 5.4 and 5.5 support since Symfony 3 requires php >= 5.5 and PHPUnit does not include the namespaced TestCase class. Also they did not receive security updates >6 months by now.
    • Dropped hhvm from the travis build since phpunit does not support hhvm: https://github.com/sebastianbergmann/phpunit/issues/2581

    An alternative, less aggressive PR can be found at #60.

    opened by nicoschoenmaker 4
  • Better interface and minor improvements

    Better interface and minor improvements

    Hi there,

    Thank you for this OS project which we use in different projects. I took some time to improve the overall lib public interface in order to clarify its integration.

    Done

    • [x] Added GaugeableCollector interface
    • [x] Resets of InfluxDB::$data in InfluxDB::flush()
    • [x] Comment consistency
    • [x] Double-quote converted into single-quote when possible
    • [x] Small code reformatting

    Hope this PR will be a small step to better the project.

    Thanks!

    opened by eexit 4
  • Sets instance variables on InMemory collector to be protected

    Sets instance variables on InMemory collector to be protected

    In order to prove out some basic metrics collection, I wanted to extend the InMemory class and customize the behavior of flush. This PR just makes the instance variables of InMemory protected so that I'm able to access them in my flush implementation.

    opened by jnbeaver 0
  • Split InfluxDB collector into two (leave current intact and introduce a separate one for official influxdb integration)

    Split InfluxDB collector into two (leave current intact and introduce a separate one for official influxdb integration)

    Hey @lyrixx

    here is an attempt to separate current InfluxDB integration and a new one using official package. This, if accepted, should replace #68 .

    Unfortunately both packages use the same namespace InfluxDB so the new one isn't covered by tests. Any advice how to handle it correctly?

    opened by andrejbaran 2
  • Timing documentation seems inconsistent

    Timing documentation seems inconsistent

    It looks like the example documentation on how to use the timing functionality isn't consistent with the expected data type and unit of measure:

    README.md:

    $start = microtime(true);
    $diff  = microtime(true) - $start;
    $collector->timing('foo.bar', $diff);
    

    In this example, $diff will be a float representing the time delta value in microseconds, while the interface expects an int representing milliseconds:

    Collector.php:

        /**
         * Records a timing.
         *
         * @param string $variable
         * @param int    $time     The duration of the timing in milliseconds
         */
        public function timing($variable, $time);
    
    opened by alexkokkinos 1
  • Add flush() to GaugeableCollector interface

    Add flush() to GaugeableCollector interface

    The flush method is required regardless of which collector type you're using. By adding this method to the GaugeableCollector interface, the collector type can be type-hinted on by the interface, rather than the implementation.

    E.g. I can write

    public function deliverMetrics(GaugeableCollector $collector) {
    	$collector->gauge('metric', 1);
    	$collector->flush();
    }
    

    instead of

    public function deliverMetrics(StatsD $collector) {
    	$collector->gauge('metric', 1);
    	$collector->flush();
    }
    
    opened by bartboy011 1
Owner
Benjamin Eberlei
Founder of @tideways, PHP performance monitoring, profiling and exception tracking software. @doctrine core member and occasional @php contributor
Benjamin Eberlei
Lock library to provide serialized execution of PHP code.

Requirements | Installation | Usage | License and authors | Donations php-lock/lock This library helps executing critical code in concurrent situation

null 875 Jan 7, 2023
Mutex lock implementation

Yii Mutex This package provides mutex implementation and allows mutual execution of concurrent processes in order to prevent "race conditions". This i

Yii Software 30 Dec 28, 2022
Test and enforce architectural rules in your Laravel applications. Keep your app's architecture clean and consistent!

Laravel Arkitect Laravel Arkitect lets you test and enforce your architectural rules in your Laravel applications, and it's a PHPArkitect wrapper for

SMorteza Ebadi 55 Dec 17, 2022
A simple functional programming library for PHP

bingo-functional A simple functional programming library for PHP. Requirement(s) PHP 7 or higher Rationale PHP, a language not commonly associated wit

Lochemem Bruno Michael 52 Sep 28, 2022
Small library providing some functional programming tools for PHP, based on Rambda

Functional library for PHP. Features: set of useful functions helpful in functional programming all functions are automatically curried every array ca

Wojciech Nawalaniec 5 Jun 16, 2022
This library uses GD and EXIF (optional) PHP extensions so make sure you have them installed.

simple and fast image processing class that can downscale, compress and convert images using php-gd native functions

Leon 8 Jul 15, 2022
SEOstats is a powerful open source PHP library to request a bunch of SEO relevant metrics.

SEOstats: SEO metrics library for PHP SEOstats is the open source PHP library to get SEO-relevant website metrics. SEOstats is used to gather metrics

Stephan Schmitz 1.4k Dec 28, 2022
Simple libary for functional programing paradigm with arrays.

rodrigodornelles/php-array-lib simple libary for functional programing paradigm with arrays Features Test driven development style (TDD) PHP version c

null 10 Nov 28, 2022
JSONFinder - a library that can find json values in a mixed text or html documents, can filter and search the json tree, and converts php objects to json without 'ext-json' extension.

JSONFinder - a library that can find json values in a mixed text or html documents, can filter and search the json tree, and converts php objects to json without 'ext-json' extension.

Eboubaker Eboubaker 2 Jul 31, 2022
A tool for diff'ing this and OpenTHC lab metrics, creating their objects, and docs.

wcia-analytes-tool Consumes OpenTHC Lab Metrics and WCIA Analytes, and produces diff objects and docs for use in WA State interop. version 0.9.8 Getti

Confidence Analytics 1 Jan 15, 2022
Sitepackage for TYPO3 CMS that adheres to the recommended standards, maps all conceivable functional areas and contains examples for common use cases.

TYPO3 CMS Sitepackage This sitepackage sticks as closely as possible to the recommended standard and maps all conceivable functional areas. There are

Eric Bode 3 Dec 18, 2022
Provides different language SDKs for the Overledger V2 API

overledger-sdks This github repository provides different language SDKs, which can be found in the SDK folder, for the Overledger DLT API Gateway. How

Quant Network 4 Oct 31, 2022
A collection of type-safe functional data structures

lamphpda A collection of type-safe functional data structures Aim The aim of this library is to provide a collection of functional data structures in

Marco Perone 99 Nov 11, 2022
N2Web turns your Notion HTML export into a fully functional static website

Notion2Web N2Web turns your Notion HTML export into a fully functional static website. What is Notion? Notion is an online tool. But I can't tell you

Lars Lehmann 15 Nov 23, 2022
WARNING! This software is currently non-functional. - A system which makes installing Jexactyl far, far easier.

Jexactyl Assistant A system which makes installing Jexactyl far, far easier. WARNING ?? This software is currently in heavy alpha testing and WILL NOT

Jexactyl 7 Nov 14, 2022
This composer plugin removes unnecessary development files and directories from vendor directory

Composer Vendor Cleaner This composer plugin removes unnecessary development files and directories from vendor directory. Installation Local installat

Libor M. 15 Dec 16, 2022
Json-normalizer: Provides generic and vendor-specific normalizers for normalizing JSON documents

json-normalizer Provides generic and vendor-specific normalizers for normalizing JSON documents. Installation Run $ composer require ergebnis/json-nor

null 64 Dec 31, 2022
Victor The Cleaner for Composer - This tool removes unnecessary files and directories from Composer vendor directory.

Victor The Cleaner for Composer This tool removes unnecessary files and directories from Composer vendor directory. The Cleaner leaves only directorie

David Grudl 133 Oct 26, 2022