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

Prometheus Monitoring Bundle Laravel Package

3slab/prometheus-monitoring-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require 3slab/prometheus-monitoring-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        Suez\PrometheusMonitoringBundle\SuezPrometheusMonitoringBundle::class => ['all' => true],
    ];
    
  2. First Use Case:

    • Metrics: Visit /metrics to expose Prometheus-formatted metrics (powered by tweedegolf/prometheus-bundle).
    • Health: Visit /health for a simple endpoint compatible with Prometheus Blackbox Exporter.
  3. Configuration: Check config/packages/suez_prometheus_monitoring.yaml for defaults. Override as needed:

    suez_prometheus_monitoring:
        metrics:
            enabled: true
            route: /metrics
        health:
            enabled: true
            route: /health
    

Implementation Patterns

Core Workflows

  1. Metrics Collection:

    • Use Prometheus\CollectorRegistry to register custom metrics:
      use Prometheus\RenderTextFormat;
      use Prometheus\CollectorRegistry;
      
      $registry = new CollectorRegistry();
      $registry->getOrRegisterCounter('app_requests_total', 'Total app requests', ['method']);
      
    • Inject the registry into services via dependency injection.
  2. Health Checks:

    • Extend the health endpoint by adding custom checks:
      // src/EventListener/HealthCheckListener.php
      public function onKernelRequest(GetResponseEvent $event)
      {
          if ($event->getRequest()->getPathInfo() === '/health') {
              $health = new HealthCheck();
              $health->addCheck(new DatabaseCheck());
              $health->addCheck(new CacheCheck());
              return new Response($health->check());
          }
      }
      
  3. Integration with Prometheus:

    • Configure Prometheus to scrape /metrics:
      # prometheus.yml
      scrape_configs:
        - job_name: 'laravel_app'
          scrape_interval: 15s
          static_configs:
            - targets: ['your-app:8000']
      

Advanced Patterns

  • Dynamic Metrics: Use middleware to track request metrics:

    // app/Http/Middleware/TrackMetrics.php
    public function handle($request, Closure $next)
    {
        $start = microtime(true);
        $response = $next($request);
        $duration = microtime(true) - $start;
    
        $registry->getOrRegisterHistogram('http_request_duration_seconds')
                 ->observe($duration, ['method' => $request->method(), 'path' => $request->path()]);
    
        return $response;
    }
    
  • Custom Health Checks:

    • Implement Suez\PrometheusMonitoringBundle\HealthCheck\HealthCheckInterface:
      class QueueCheck implements HealthCheckInterface
      {
          public function check(): bool
          {
              return Queue::size() < 1000;
          }
      
          public function getMessage(): string
          {
              return 'Queue size is healthy';
          }
      }
      

Gotchas and Tips

Common Pitfalls

  1. Deprecated Bundle:

    • This bundle is unmaintained. Use VdmPrometheusBundle for new projects.
    • Metrics may break if underlying tweedegolf/prometheus-bundle dependencies diverge.
  2. Route Conflicts:

    • Ensure /metrics and /health routes don’t clash with existing routes. Override in routes.yaml:
      suez_prometheus_monitoring:
          health:
              route: /app_health
      
  3. Performance Overhead:

    • Metrics collection adds minimal overhead, but avoid excessive custom metrics in high-traffic endpoints.

Debugging Tips

  • Metrics Not Showing?:

    • Verify the Prometheus\CollectorRegistry is properly injected and metrics are registered before the request lifecycle ends.
    • Check Symfony’s profiler (/_profiler) for errors during metric collection.
  • Health Endpoint Failing:

    • Ensure all custom health checks return true or implement proper error handling:
      public function check(): bool
      {
          try {
              return DB::connection()->getPdo();
          } catch (\Exception $e) {
              return false;
          }
      }
      

Extension Points

  1. Custom Metrics:

    • Extend the bundle by overriding the metric registry in a compiler pass:
      // src/Kernel.php
      protected function registerContainerConfiguration(LoaderInterface $loader)
      {
          $loader->load(function (ContainerBuilder $container) {
              $container->getDefinition('suez_prometheus_monitoring.registry')
                        ->setMethodCalls([
                            ['register', [new CustomMetric()]],
                        ]);
          });
      }
      
  2. Health Check Templates:

    • Override the health response template by publishing assets:
      php artisan vendor:publish --tag=suez-prometheus-monitoring-assets
      
    • Modify templates/health.html.twig to customize the output format.
  3. Prometheus Labels:

    • Add dynamic labels to metrics using Symfony’s RequestStack:
      $labels = [
          'user_id' => $request->user()->id,
          'locale' => $request->getLocale(),
      ];
      $registry->getOrRegisterCounter('custom_metric')->inc($labels);
      

---
```markdown
### Configuration Quirks
- **Blackbox Exporter Compatibility**:
  The `/health` endpoint expects a **200 OK** response for healthy checks. Non-200 responses (e.g., 500) will trigger alerts in Prometheus.
  Example for Prometheus Blackbox Exporter config:
  ```yaml
  modules:
    http_2xx:
      prober: http
      http:
        valid_status_codes: [200]
  • Caching Metrics: Disable caching for /metrics to ensure real-time data:
    # config/packages/framework.yaml
    framework:
        http_cache:
            invalidation:
                paths: ['^/(?!metrics$)']
    
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