PHP code example of ez-php / metrics

1. Go to this page and download the library: Download ez-php/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/ */

    

ez-php / metrics example snippets


\EzPhp\Metrics\MetricsServiceProvider::class,

use EzPhp\Metrics\Metrics;

Metrics::counter('http_requests_total', 'Total HTTP requests')
    ->inc(['method' => 'GET', 'status' => '200']);

Metrics::counter('bytes_sent_total', 'Total bytes sent')
    ->incBy(1024.0);

Metrics::gauge('memory_usage_bytes', 'Current memory usage')
    ->set((float) memory_get_usage());

Metrics::gauge('active_connections', 'Active connections')
    ->inc();

Metrics::gauge('queue_depth', 'Queue depth')
    ->dec(['queue' => 'default']);

$start = microtime(true);
// ... handle request ...
Metrics::histogram('request_duration_seconds', 'Request duration in seconds')
    ->observe(microtime(true) - $start, ['route' => '/api/users']);

Metrics::histogram('response_size_bytes', 'Response size', [100, 1000, 10000, 100000])
    ->observe((float) strlen($responseBody));

use EzPhp\Metrics\MetricsRegistry;
use EzPhp\Metrics\RequestMetricsMiddleware;
use EzPhp\Routing\Router;

// in a service provider's register()
$this->app->bind(RequestMetricsMiddleware::class, fn ($app) => new RequestMetricsMiddleware(
    $app->make(MetricsRegistry::class),
    static fn (): ?string => $app->make(Router::class)->matchedRoute()?->getPath(),
));

// bootstrap
$app->middleware(RequestMetricsMiddleware::class);

// config/metrics.php
return [
    'endpoint' => false, // or METRICS_ENDPOINT= (empty)
];

// routes/web.php
use EzPhp\Metrics\MetricsController;

$router->get('/metrics', [MetricsController::class, '__invoke'])
    ->middleware(App\Middleware\MetricsAuthMiddleware::class);

use EzPhp\Metrics\HealthMetricsListener;

$listener = new HealthMetricsListener($healthRegistry, $metricsRegistry);
$listener->record(); // before serving /metrics, or on a schedule — your call
bash
composer