PHP code example of jarir-ahmed / server-stats

1. Go to this page and download the library: Download jarir-ahmed/server-stats 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/ */

    

jarir-ahmed / server-stats example snippets


use JarirAhmed\ServerStats\{Storage, Metrics, MetricCollector};

$storage = new Storage(); // MySQL if reachable, else SQLite in the system temp dir
Metrics::init($storage);

// Counter — atomic, durable across requests/processes
Metrics::counter('page_views.home')->increment();

// Gauge — point-in-time value (latest wins)
Metrics::gauge('queue.depth')->set(42);

// Timer — measure a block; stops even if the callback throws
$result = Metrics::measure('request.processing', function () {
    return doWork();
});

// System metrics (CPU load, memory, disk)
(new MetricCollector($storage))->recordSystemMetrics();

$storage = new Storage([
    'host'             => '127.0.0.1',
    'port'             => '3306',
    'database'         => 'server_stats',
    'username'         => 'root',
    'password'         => '',
    'charset'          => 'utf8mb4',
    'sqlite_path'      => '/var/data/server_stats.db', // SQLite fallback location
    'retention_seconds'=> 7 * 86400,  // auto-prune samples older than this (0 = off)
    'gc_probability'   => 0.01,        // chance per save() of running a prune sweep
    'logger'           => fn(string $m) => error_log($m),
]);

Metrics::counter('http.requests', ['status' => 200])->increment();
Metrics::counter('http.requests', ['status' => 500])->increment();

Metrics::counter('http.requests', ['status' => 200])->getValue(); // 1.0

$storage->getLatest(20);                       // recent time-series samples (newest first)
$storage->getCounters();                       // all counters
$storage->query(['name' => 'request.processing_ms', 'since' => time() - 3600]);
$storage->aggregate('request.processing_ms', 'avg', time() - 3600); // avg|min|max|sum|count
$storage->prune(7 * 86400);                    // delete samples older than 7 days

use JarirAhmed\ServerStats\{Registry, InMemoryStorage};

$registry = new Registry(new InMemoryStorage());
$registry->counter('hits')->increment();
$registry->gauge('temp')->set(21.5);