Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Prometheus Laravel Package

spatie/laravel-prometheus

Export Laravel app metrics to Prometheus via a /prometheus endpoint. Register custom gauges/counters with simple callbacks, use built-in queue and Horizon metrics, and optionally secure the endpoint. Ideal for scraping by Prometheus and charting in Grafana.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/laravel-prometheus
    

    Publish the config file:

    php artisan vendor:publish --provider="Spatie\Prometheus\PrometheusServiceProvider"
    
  2. Configuration: Edit config/prometheus.php to define:

    • host (default: 127.0.0.1)
    • port (default: 9256)
    • metrics (enabled/disabled metrics like laravel, queue, cache, etc.)
  3. First Use Case: Start the Prometheus server:

    php artisan prometheus:server
    

    Access metrics at http://localhost:9256/metrics. Verify Laravel-specific metrics (e.g., laravel_request_duration_seconds) appear in the output.


Where to Look First

  • Documentation: Spatie’s Laravel Prometheus Docs (covers setup, custom metrics, and integration).
  • Config File: config/prometheus.php (toggle metrics, adjust endpoints).
  • Metrics Endpoint: /metrics (validate data exposure).

Implementation Patterns

Core Workflows

  1. Default Metrics: Automatically exposes:

    • HTTP request metrics (status codes, duration, size).
    • Queue metrics (job processing time, failures).
    • Cache metrics (hit/miss ratios).
    • Database metrics (query duration, count).
    • Laravel-specific metrics (e.g., laravel_routes_count).
  2. Custom Metrics: Use the PrometheusRegistrar facade to define custom metrics:

    use Spatie\Prometheus\Facades\PrometheusRegistrar;
    
    PrometheusRegistrar::gauge('my_app.custom_metric', 'Custom metric description');
    PrometheusRegistrar::set('my_app.custom_metric', 42);
    

    Register custom metrics in a service provider’s boot() method.

  3. Conditional Metrics: Disable metrics in config/prometheus.php for performance-sensitive environments:

    'metrics' => [
        'laravel' => env('APP_ENV') !== 'production',
        'queue'   => true,
    ],
    
  4. Integration with Monitoring Tools:

    • Point Prometheus to your Laravel app’s /metrics endpoint.
    • Use Grafana for visualization (import pre-built Laravel dashboards from Grafana.com).

Advanced Patterns

  1. Dynamic Metrics: Track dynamic values (e.g., user-specific metrics) using labels:

    PrometheusRegistrar::gauge('user_activity', 'User activity count', ['user_id']);
    PrometheusRegistrar::set('user_activity', ['user_id' => 123], 10);
    
  2. Middleware for Request Metrics: Extend request tracking with middleware:

    public function handle($request, Closure $next) {
        $start = microtime(true);
        $response = $next($request);
        $duration = microtime(true) - $start;
    
        PrometheusRegistrar::histogram('custom_request_duration_seconds')
            ->labels(['route' => $request->route()->getName()])
            ->observe($duration);
    
        return $response;
    }
    
  3. Health Checks: Expose a /health endpoint alongside /metrics to validate Prometheus connectivity:

    Route::get('/health', function () {
        return response()->json(['status' => 'ok']);
    });
    
  4. Environment-Specific Config: Use environment variables to toggle metrics in .env:

    PROMETHEUS_ENABLED=true
    PROMETHEUS_METRICS="laravel,queue"
    

    Then reference in config/prometheus.php:

    'enabled' => env('PROMETHEUS_ENABLED', true),
    'metrics' => explode(',', env('PROMETHEUS_METRICS', 'laravel,queue,cache')),
    

Gotchas and Tips

Common Pitfalls

  1. Port Conflicts:

    • Default port 9256 may clash with other services. Change in config/prometheus.php:
      'port' => env('PROMETHEUS_PORT', 9257),
      
    • Verify no firewall blocks the port:
      sudo ufw allow 9257
      
  2. Performance Overhead:

    • Disable unnecessary metrics in production to reduce CPU/memory usage.
    • Monitor Prometheus server resource usage (htop or docker stats).
  3. Metric Naming Collisions:

    • Avoid naming custom metrics with prefixes like laravel_ or prometheus_ to prevent conflicts with built-in metrics.
    • Use a unique namespace (e.g., myapp_custom_metric).
  4. Prometheus Scraping Issues:

    • Ensure Prometheus can reach the Laravel app’s /metrics endpoint (check CORS, auth, or network policies).
    • Test scraping manually:
      curl http://localhost:9256/metrics
      

Debugging Tips

  1. Log Metric Updates: Enable debug logging in config/prometheus.php:

    'debug' => env('APP_DEBUG', false),
    

    Check storage/logs/laravel.log for metric-related entries.

  2. Validate Metric Exposure: Use curl to inspect raw metrics:

    curl -v http://localhost:9256/metrics | grep "laravel_"
    
  3. Prometheus Configuration: Validate prometheus.yml targets:

    scrape_configs:
      - job_name: 'laravel'
        static_configs:
          - targets: ['laravel-app:9256']
    

    Restart Prometheus after changes:

    prometheus --config.file=prometheus.yml
    

Extension Points

  1. Custom Metric Types: Extend beyond gauges/histograms by implementing Spatie\Prometheus\Metric\MetricInterface:

    class CustomCounter implements MetricInterface {
        public function collect(): string { /* ... */ }
    }
    

    Register via PrometheusRegistrar::registerMetric().

  2. Dynamic Metric Labels: Use closures for dynamic labels:

    PrometheusRegistrar::gauge('dynamic_metric', function () {
        return ['user_id' => auth()->id()];
    });
    
  3. Prometheus Server Hooks: Override the server boot process in a service provider:

    public function boot() {
        $this->app->make(Spatie\Prometheus\PrometheusServiceProvider::class)
            ->registerServer(function ($server) {
                $server->addCollector(new CustomCollector());
            });
    }
    
  4. Metric Aggregation: Use Prometheus’s built-in functions (sum, avg) to aggregate custom metrics in queries:

    sum(laravel_request_duration_seconds_bucket{le="0.5"}) by (route)
    

Configuration Quirks

  1. Environment Variables: Prefix config keys with PROMETHEUS_ for clarity:

    PROMETHEUS_HOST=0.0.0.0
    PROMETHEUS_PORT=9256
    

    Access in config:

    'host' => env('PROMETHEUS_HOST', '127.0.0.1'),
    
  2. Docker Integration: Expose the port in docker-compose.yml:

    services:
      laravel:
        ports:
          - "9256:9256"
    

    Use links or Docker networks for Prometheus-Laravel communication.

  3. Queue Worker Metrics: Ensure queue workers are running with the same Laravel environment (e.g., same .env) to expose consistent metrics.

  4. Caching Metrics: Disable caching for /metrics in routes/web.php:

    Route::get('/metrics', function () {
        return Spatie\Prometheus\Facades\PrometheusRegistrar::metrics();
    })->middleware('throttle:60,1'); // Limit scraping rate
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport