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

Tweedegolf Prometheus Bundle Laravel Package

3slab/tweedegolf-prometheus-bundle

Symfony bundle integrating the Tweede Golf Prometheus client. Configure a /metrics endpoint, choose a storage adapter, and define counters/gauges/histograms via YAML collectors. Update metrics through the CollectorRegistry service in your app.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require tweedegolf/prometheus-bundle
    
  2. Register the Bundle Add to config/bundles.php (Symfony 4+):

    return [
        // ...
        TweedeGolf\PrometheusBundle\TweedeGolfPrometheusBundle::class => ['all' => true],
    ];
    
  3. Expose Metrics Endpoint Add to config/routes.yaml:

    tweede_golf_prometheus:
        resource: "@TweedeGolfPrometheusBundle/Resources/config/routing.yml"
        prefix: /
    
  4. Verify Endpoint Access /metrics in your browser or via curl to confirm the Prometheus endpoint is live.


First Use Case: Tracking HTTP Requests

  1. Define a Collector Configure in config/packages/tweede_golf_prometheus.yaml:

    tweede_golf_prometheus:
        collectors:
            http_requests:
                counter:
                    labels: [method, endpoint]
                    help: "Number of HTTP requests by method and endpoint"
    
  2. Increment Metrics in Code

    use TweedeGolf\PrometheusClient\CollectorRegistry;
    
    public function someAction(Request $request, CollectorRegistry $registry)
    {
        $metric = $registry->getCounter('http_requests');
        $metric->inc([$request->getMethod(), $request->getPathInfo()]);
    }
    

Implementation Patterns

Core Workflow: Metrics Collection

  1. Define Metrics in Config Use collectors to declare counters, gauges, or histograms with labels and help text. Example:

    tweede_golf_prometheus:
        collectors:
            database_queries:
                histogram:
                    labels: [query_type]
                    help: "Database query execution time (seconds)"
                    buckets: [0.1, 0.5, 1, 2.5, 5]
    
  2. Inject and Use CollectorRegistry Autowire the service in controllers/services:

    public function logQueryTime(CollectorRegistry $registry, float $duration, string $type)
    {
        $histogram = $registry->getHistogram('database_queries');
        $histogram->observe([$type], $duration);
    }
    
  3. Leverage Symfony Events Attach collectors to events (e.g., kernel.request) for automatic metrics:

    services:
        app.prometheus.request_collector:
            class: App\Service\Prometheus\RequestCollector
            tags:
                - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
                - { name: tweede_golf_prometheus.collector }
    

Advanced Patterns

  1. Dynamic Collectors Register collectors programmatically via CollectorRegistry:

    $registry->createGauge('dynamic_gauge', 'Dynamic gauge example', ['label1']);
    
  2. Custom Storage Adapters Override the default ApcuAdapter for production (e.g., Redis):

    tweede_golf_prometheus:
        storage_adapter_service: app.prometheus.redis_adapter
    

    Define the service:

    services:
        app.prometheus.redis_adapter:
            class: App\Prometheus\RedisAdapter
            arguments: ['@redis']
            public: true
    
  3. Integration with Monolog Log metrics to Prometheus via Monolog handlers (requires custom handler).


Gotchas and Tips

Pitfalls

  1. Deprecated Symfony Features

    • The bundle assumes Symfony 3/4 autowiring but lacks explicit Symfony 5+ support.
    • Fix: Manually configure services if using Symfony 5+:
      services:
          TweedeGolf\PrometheusClient\CollectorRegistry: ~
      
  2. Storage Adapter Limitations

    • Default ApcuAdapter is memory-bound and unsuitable for clustered environments.
    • Tip: Use Redis or a custom adapter for distributed setups.
  3. Label Cardinality Explosion

    • Overusing labels (e.g., user_id) can bloat metrics.
    • Tip: Limit labels to high-cardinality dimensions (e.g., endpoint, status_code).
  4. Metric Naming Conflicts

    • Duplicate collector names (e.g., two requests counters) will overwrite each other.
    • Tip: Use unique names (e.g., api_requests, cli_requests).

Debugging

  1. Verify Metrics Endpoint

    • Check /metrics for 404 or malformed output.
    • Fix: Ensure metrics_path is correctly configured and the route is exposed.
  2. Missing Metrics

    • If metrics aren’t incrementing, verify:
      • The collector name matches the config.
      • The CollectorRegistry service is properly injected.
    • Debug: Dump the registry:
      dump($registry->getCollectors());
      
  3. Storage Adapter Issues

    • APCu errors (e.g., APCu not installed) will break metrics.
    • Fix: Install APCu or switch adapters:
      pecl install apcu
      

Extension Points

  1. Custom Collectors Implement TweedeGolf\PrometheusClient\Collector\CollectorInterface:

    class CustomCollector implements CollectorInterface
    {
        public function collect(): array { /* ... */ }
    }
    

    Register with:

    tags:
        - { name: tweede_golf_prometheus.collector }
    
  2. Modify Metrics Mid-Flight Use CollectorRegistry to update metrics dynamically:

    $gauge = $registry->getGauge('memory_usage');
    $gauge->set(memory_get_usage(true) / 1024 / 1024); // MB
    
  3. Prometheus Relabeling Extend the bundle to support relabeling rules (requires custom middleware).


Pro Tips

  • Use Histograms for Latency: Track request durations with buckets:
    response_times:
        histogram:
            buckets: [0.05, 0.1, 0.25, 0.5, 1, 2.5, 5]
    
  • Avoid Gauge Pollution: Gauges should represent instantaneous values (e.g., active_users), not accumulators.
  • Test Locally: Use promtool to validate metrics:
    docker run --rm prom/prometheus tools/promtool check 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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui