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

Vdm Prometheus Bundle Laravel Package

3slab/vdm-prometheus-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle via Composer:

    composer require 3slab/vdm-prometheus-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        Vdm\PrometheusBundle\VdmPrometheusBundle::class => ['all' => true],
    ];
    
  2. Configuration Publish the default config (optional):

    php bin/console vdm:prometheus:install
    

    Edit config/packages/vdm_prometheus.yaml to adjust:

    • Endpoint path (default: /metrics)
    • Environment whitelist (e.g., dev)
  3. First Use Case Access the metrics endpoint at /metrics (or your configured path) and scrape it with Prometheus:

    # prometheus.yml
    scrape_configs:
      - job_name: 'laravel_app'
        static_configs:
          - targets: ['your-app:8000']
    

Implementation Patterns

Core Workflows

  1. Automatic Metrics Collection The bundle hooks into Symfony’s kernel events (kernel.request, kernel.response) to track:

    • Route-level metrics: Memory usage, execution time, response size.
    • HTTP response codes: Counters per route and status code (e.g., 200, 500).
    • Global app metrics: Total API calls (vdm_sf_app_call_total).
  2. Custom Metrics Extend the bundle by creating custom collectors. Example:

    // src/Collector/CustomCollector.php
    namespace App\Collector;
    
    use Prometheus\Collector;
    
    class CustomCollector extends Collector {
        public function collect() {
            $this->metrics['app_custom_metric'] = new Gauge([
                'help' => 'Custom metric example',
                'label_names' => ['type'],
            ]);
            $this->metrics['app_custom_metric']->set([], 42);
        }
    }
    

    Register in config/packages/vdm_prometheus.yaml:

    vdm_prometheus:
        collectors:
            - App\Collector\CustomCollector
    
  3. Middleware Integration Use the bundle’s metrics in middleware for granular tracking:

    // app/Http/Middleware/TrackCustomMetric.php
    public function handle($request, Closure $next) {
        $start = microtime(true);
        $response = $next($request);
        $duration = microtime(true) - $start;
    
        // Manually update a custom metric (if needed)
        $this->prometheus->getCollector('custom')->set([], $duration);
        return $response;
    }
    
  4. Environment-Specific Scraping Restrict the /metrics endpoint to specific environments (e.g., dev, staging) via config:

    vdm_prometheus:
        allowed_environments: ['dev', 'staging']
    

Integration Tips

  • Prometheus Alerts: Use the collected metrics (e.g., vdm_sf_app_response_code_total{http_code="500"}) to trigger alerts for error spikes.
  • Grafana Dashboards: Visualize metrics like:
    • Response time percentiles (via histogram_quantile).
    • Memory trends per route.
    • Error rate by route (vdm_sf_app_response_code_total).
  • Laravel-Specific: Combine with Laravel’s debugbar for local development insights, then switch to Prometheus for production.

Gotchas and Tips

Pitfalls

  1. Performance Overhead

    • Issue: Metrics collection adds minimal overhead (~1-5ms per request). Test under load to ensure it doesn’t impact critical paths.
    • Fix: Disable in production if unused or restrict to non-critical routes.
  2. Memory Leaks

    • Issue: Long-running requests (e.g., CLI commands) may skew memory metrics.
    • Fix: Exclude CLI routes from tracking via config:
      vdm_prometheus:
          ignore_routes:
              - '^_wdt/'
              - '^_profiler/'
      
  3. Label Collisions

    • Issue: Custom labels with dynamic values (e.g., user IDs) can explode cardinality.
    • Fix: Limit labels to high-level dimensions (e.g., route, http_code).
  4. Prometheus Scrape Failures

    • Issue: Endpoint returns 403 if environment isn’t whitelisted.
    • Fix: Verify allowed_environments in config and check Prometheus’s scrape_interval.

Debugging

  • Log Metrics: Enable debug mode to log collected metrics:
    vdm_prometheus:
        debug: true
    
  • Validate Endpoint: Test the /metrics endpoint manually:
    curl http://localhost:8000/metrics
    
    Expected output: Prometheus exposition format (as shown in README).

Extension Points

  1. Custom Metric Types Add support for Histogram or Summary metrics by extending the bundle’s collector:

    // src/Collector/RequestDurationHistogram.php
    use Prometheus\Histogram;
    
    class RequestDurationHistogram extends Collector {
        public function collect() {
            $this->metrics['request_duration_seconds'] = new Histogram([
                'help' => 'Request duration in seconds',
                'label_names' => ['route'],
                'buckets' => [0.1, 0.5, 1, 2.5, 5],
            ]);
        }
    }
    
  2. Event-Based Hooks Listen to vdm_prometheus.collect events to inject custom logic:

    // src/EventListener/CustomMetricsListener.php
    public function onCollect(CollectEvent $event) {
        $event->getCollector()->addMetric('custom_metric', 123);
    }
    

    Register in services.yaml:

    services:
        App\EventListener\CustomMetricsListener:
            tags:
                - { name: 'kernel.event_listener', event: 'vdm_prometheus.collect' }
    
  3. Exclude Routes Skip metrics for specific routes (e.g., health checks):

    vdm_prometheus:
        ignore_routes:
            - '^health$'
    

Config Quirks

  • Default App Label: The app label in metrics defaults to app. Override via:
    vdm_prometheus:
        app_name: 'my_laravel_app'
    
  • Response Size: Measures raw response bytes (including headers). For body-only size, use a custom collector.
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope