PHP code example of saimaz / laravel-prometheus

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

    

saimaz / laravel-prometheus example snippets


'http' => [
    'ignored_routes' => ['metrics', 'horizon.*', 'health', 'telescope.*'],
],



namespace App\Prometheus;

use Ninebit\LaravelPrometheus\Contracts\MetricDefinition;

enum Metric: string implements MetricDefinition
{
    case API_CALLS = 'external_api_calls_total';
    case API_DURATION = 'external_api_duration_seconds';
    case ACTIVE_SESSIONS = 'active_sessions_total';

    public function helpText(): string
    {
        return match ($this) {
            self::API_CALLS => 'Total external API calls',
            self::API_DURATION => 'External API call duration',
            self::ACTIVE_SESSIONS => 'Number of active user sessions',
        };
    }

    public function labelNames(): array
    {
        return match ($this) {
            self::API_CALLS => ['service', 'status'],
            self::API_DURATION => ['service', 'endpoint'],
            self::ACTIVE_SESSIONS => ['guard'],
        };
    }

    public function buckets(): ?array
    {
        return match ($this) {
            self::API_DURATION => [0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0],
            default => null,
        };
    }
}

use App\Prometheus\Metric;
use Ninebit\LaravelPrometheus\Contracts\MetricsRegistryInterface;

class EmailService
{
    public function __construct(
        private readonly MetricsRegistryInterface $metrics,
    ) {}

    public function send(string $template): void
    {
        $start = hrtime(true);

        // ... call external mail provider API ...

        $this->metrics->observeDuration(Metric::API_DURATION, $start, ['mailgun', '/v3/messages']);
        $this->metrics->counter(Metric::API_CALLS)->incBy(1, ['mailgun', 'success']);
    }
}

use Ninebit\LaravelPrometheus\Facades\Prometheus;

Prometheus::gauge(Metric::ACTIVE_SESSIONS)->set(42, ['web']);



namespace App\Prometheus\Collectors;

use App\Prometheus\Metric;
use Ninebit\LaravelPrometheus\Contracts\CollectorInterface;
use Ninebit\LaravelPrometheus\Contracts\MetricsRegistryInterface;
use Illuminate\Support\Facades\DB;

class ActiveSessionsCollector implements CollectorInterface
{
    public function collect(MetricsRegistryInterface $registry): void
    {
        // Example: count active sessions from a database table
        $count = DB::table('sessions')
            ->where('last_activity', '>=', now()->subMinutes(15)->getTimestamp())
            ->count();

        $registry->gauge(Metric::ACTIVE_SESSIONS)->set($count, ['web']);
    }
}

'collectors' => [
    \App\Prometheus\Collectors\ActiveSessionsCollector::class,
],



namespace App\Prometheus;

use Illuminate\Http\Request;
use Ninebit\LaravelPrometheus\Contracts\HttpLabelProvider;
use Symfony\Component\HttpFoundation\Response;

class TenantLabelProvider implements HttpLabelProvider
{
    public function labelNames(): array
    {
        return ['tenant', 'route', 'method', 'status'];
    }

    public function labelValues(Request $request, Response $response): array
    {
        return [
            $request->header('X-Tenant-ID', 'default'),
            $request->route()?->getName() ?? $request->route()?->uri() ?? 'unnamed',
            $request->getMethod(),
            (string) $response->getStatusCode(),
        ];
    }
}

'http' => [
    'label_provider' => \App\Prometheus\TenantLabelProvider::class,
],
bash
php artisan vendor:publish --tag=prometheus-config