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 Metrics Bundle Laravel Package

artprima/prometheus-metrics-bundle

Symfony bundle integrating promphp/prometheus_client_php to expose Prometheus metrics for your app. Supports Symfony 5.4–8.x and PHP 8.2–8.5, with configurable metric namespace, ignored routes, and custom labels for HTTP/request metrics.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require artprima/prometheus-metrics-bundle
    
  2. Enable the Bundle: Add to config/bundles.php:

    Artprima\PrometheusMetricsBundle\ArtprimaPrometheusMetricsBundle::class => ['all' => true],
    
  3. Expose Metrics Endpoint: Add to config/routes.yaml:

    app_metrics:
        resource: '@ArtprimaPrometheusMetricsBundle/Resources/config/routing.yaml'
    
  4. Verify: Access /metrics/prometheus in your browser or via curl to see default metrics.

First Use Case: Monitoring HTTP Requests

The bundle automatically tracks:

  • Request counts (http_requests_total)
  • Response status codes (http_2xx_responses_total, http_5xx_responses_total)
  • Request duration histograms (http_request_duration_seconds)

Example output:

# HELP symfony_http_requests_total total request count
# TYPE symfony_http_requests_total counter
symfony_http_requests_total{action="GET-homepage",method="GET"} 42

Implementation Patterns

Core Workflow: Custom Metrics Collection

  1. Create a Collector Class: Implement RequestMetricsCollectorInterface or ResponseMetricsCollectorInterface:

    use Artprima\PrometheusMetricsBundle\Metrics\RequestMetricsCollectorInterface;
    use Prometheus\CollectorRegistry;
    
    class CustomCollector implements RequestMetricsCollectorInterface {
        public function collectRequest(RequestEvent $event) {
            $registry = $this->getRegistry(); // Injected via init()
            $counter = $registry->getOrRegisterCounter(
                'myapp',
                'custom_metric',
                'Description',
                ['label']
            );
            $counter->inc(['value']);
        }
    }
    
  2. Automatic Registration: With autoconfigure enabled (default), tag your service:

    services:
        App\Metrics\CustomCollector:
            tags: ['prometheus_metrics_bundle.metrics_collector']
    
  3. Lifecycle Hooks: Use interfaces for specific events:

    • PreRequestMetricsCollectorInterface: Pre-request processing
    • ExceptionMetricsCollectorInterface: Error tracking
    • ConsoleCommandMetricsCollectorInterface: CLI metrics (enable via config)

Integration Tips

  • Symfony Events: Leverage kernel.request, kernel.response, and kernel.exception events for granular control.
  • Label Customization: Use labels config to attach request attributes/headers:
    labels:
        - { name: "user_id", type: "request_attribute", value: "_user_id" }
    
  • Storage Backends: Switch between in_memory, redis, or apcu via config:
    storage:
        type: redis
        host: redis.example.com
    
  • Grafana Integration: Import provided dashboards (grafana/symfony-app-overview.json) for pre-built visualizations.

Advanced Patterns

  1. Dynamic Metrics: Use MetricInfoResolverInterface to customize metric naming/labeling:

    class DynamicResolver implements MetricInfoResolverInterface {
        public function resolve(MetricInfo $metricInfo) {
            $metricInfo->setName('dynamic_' . $metricInfo->getName());
        }
    }
    
  2. Custom Storage: Implement StorageFactoryInterface for non-standard backends (e.g., database):

    class DatabaseFactory implements StorageFactoryInterface {
        public function create(array $options): Adapter {
            return new DatabaseAdapter($options['dsn']);
        }
    }
    
  3. Conditional Collection: Skip metrics for specific routes:

    ignored_routes: ['api/v1/health', 'admin/*']
    

Gotchas and Tips

Common Pitfalls

  1. Double Registration:

    • Issue: Metrics appear twice if both default and custom collectors track the same events.
    • Fix: Disable default metrics via disable_default_metrics: true in config.
  2. Label Collisions:

    • Issue: Custom labels may conflict with default labels (e.g., action).
    • Fix: Use unique label names or override the MetricInfoResolver.
  3. Redis Connection Issues:

    • Issue: Metrics disappear if Redis fails silently.
    • Fix: Configure timeouts and retries in storage.options:
      storage:
          options:
              retry_attempts: 3
              retry_delay: 100
      
  4. Console Metrics:

    • Issue: enable_console_metrics: true doesn’t work if CLI events aren’t dispatched.
    • Fix: Ensure Symfony’s ConsoleApplication is properly configured.

Debugging Tips

  • Verify Metrics Endpoint:
    curl -s http://localhost/metrics/prometheus | grep "symfony_http"
    
  • Check Event Listeners: Use Symfony’s debug toolbar or bin/console debug:event-dispatcher to confirm collectors are attached.
  • Storage Inspection: For in_memory, dump the registry:
    $registry = $container->get('prometheus.registry');
    print_r($registry->getMetricFamilySamples());
    

Performance Quirks

  1. High Cardinality Labels:

    • Problem: Too many unique label values (e.g., user_id) can bloat storage.
    • Solution: Limit labels to high-level dimensions (e.g., user_segment).
  2. Histogram Buckets:

    • Problem: Default buckets may not align with your SLA requirements.
    • Solution: Customize buckets in config:
      buckets: [0.05, 0.1, 0.5, 1, 2, 5]
      
  3. APCu/APCng:

    • Problem: Shared hosting may disable APCu, causing crashes.
    • Solution: Fall back to in_memory or Redis.

Extension Points

  1. Metric Filtering: Override Artprima\PrometheusMetricsBundle\Metrics\MetricsCollector to filter metrics dynamically:

    public function shouldCollect(RequestEvent $event): bool {
        return !$event->getRequest()->isXmlHttpRequest();
    }
    
  2. Custom Exporters: Extend Artprima\PrometheusMetricsBundle\Exporter\MetricsExporter to add OpenTelemetry or other formats.

  3. Rate Limiting: Use PreRequestMetricsCollectorInterface to enforce metric collection quotas:

    if ($this->rateLimiter->isOverLimit($request)) {
        return;
    }
    

Configuration Tricks

  • Namespace Isolation: Use distinct namespaces for microservices:
    namespace: "service-payments"
    
  • Environment-Specific: Override config per environment (e.g., disable metrics in dev):
    # config/packages/dev/artprima_prometheus_metrics.yaml
    disable_default_metrics: true
    
  • Dynamic Ignored Routes: Load ignored routes from a service:
    ignored_routes: '%env(IGNORED_ROUTES)%'
    
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor