PHP code example of kislayphp / metrics

1. Go to this page and download the library: Download kislayphp/metrics library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

kislayphp / metrics example snippets



$metrics = new Kislay\Metrics\Collector();
$metrics->counter('requests_total')->increment();
$metrics->histogram('request_duration_ms')->observe($ms);
echo $metrics->export(); // Prometheus text format


$metrics = new Kislay\Metrics\Collector();

// Counter — monotonically increasing
$metrics->counter('http_requests_total', ['method' => 'GET', 'status' => '200'])
        ->increment();

// Gauge — value that goes up and down
$metrics->gauge('active_connections')->set(42);
$metrics->gauge('queue_depth')->increment();
$metrics->gauge('queue_depth')->decrement();

// Histogram — distribution of values
$start = microtime(true);
// ... handle request ...
$metrics->histogram('request_duration_seconds')
        ->observe(microtime(true) - $start);

// Timer (convenience wrapper for histogram) — start()/stop() on the same
// object; start() returns void, not a chainable handle.
$timer = $metrics->timer('db_query_seconds');
$timer->start();
// ... run query ...
$timer->stop(); // records the elapsed time into the underlying histogram

// Export as Prometheus text format
$app->get('/metrics', function($req, $res) use ($metrics) {
    $res->send($metrics->export(), 'text/plain; version=0.0.4');
});

namespace Kislay\Metrics;

class Collector {
    public function counter(string $name, array $labels = []): Counter;
    public function gauge(string $name, array $labels = []): Gauge;
    public function histogram(string $name, array $labels = [], array $buckets = []): Histogram;
    public function timer(string $name, array $labels = []): Timer;
    public function export(): string;    // Prometheus text format
    public function reset(): void;
}

class Counter  { public function increment(float $by = 1): void; public function get(): float; }
class Gauge    { public function set(float $value): void; public function increment(float $by = 1): void; public function decrement(float $by = 1): void; public function get(): float; }
class Histogram { public function observe(float $value): void; }
class Timer    { public function __construct(string $name, Histogram $histogram); public function start(): void; public function stop(): float; public function record(float $ms): void; }