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 Client Laravel Package

tweedegolf/prometheus-client

Archived/unmaintained PHP Prometheus client by Tweede Golf. Provides Counter and Gauge metrics with multiple storage backends (e.g., APC/APCu) and a text formatter to expose a /metrics endpoint for Prometheus scraping.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require tweedegolf/prometheus-client
    

    Ensure your Laravel app has Redis and OPcache extensions installed (php -m | grep redis and php -m | grep opcache).

  2. Basic Setup:

    use TweedeGolf\PrometheusClient\CollectorRegistry;
    use TweedeGolf\PrometheusClient\Storage\ApcuAdapter;
    
    $registry = new CollectorRegistry(new ApcuAdapter());
    
  3. Define Metrics:

    $registry->createCounter('api_requests_total', [], 'Total API requests');
    $registry->createGauge('api_latency_seconds', [], 'API latency in seconds');
    
  4. Expose Metrics Endpoint (e.g., /metrics):

    use TweedeGolf\PrometheusClient\Format\TextFormatter;
    
    Route::get('/metrics', function () use ($registry) {
        $formatter = new TextFormatter();
        header('Content-Type', $formatter->getMimeType());
        return $formatter->format($registry->collect());
    });
    
  5. Update Metrics in Code:

    $registry->getCounter('api_requests_total')->inc();
    $registry->getGauge('api_latency_seconds')->set($executionTime);
    

Implementation Patterns

Core Workflows

  1. Metric Lifecycle:

    • Declaration: Define metrics once during app bootstrap (e.g., in AppServiceProvider).
    • Update: Increment counters/gauges in middleware, controllers, or services.
    • Exposure: Serve metrics via a dedicated route (e.g., /metrics).
  2. Middleware Integration:

    $registry->getCounter('api_requests_total')->inc();
    $registry->getGauge('api_latency_seconds')->set(microtime(true) - LARAVEL_START);
    
  3. Event-Based Updates:

    event(new JobProcessed($job));
    // In listener:
    $registry->getCounter('jobs_processed_total')->inc();
    
  4. Labelled Metrics:

    $registry->createCounter('http_requests_total', ['method', 'endpoint']);
    $registry->getCounter('http_requests_total')->inc(['method' => 'GET', 'endpoint' => '/users']);
    

Laravel-Specific Tips

  • Service Container Binding:

    $app->singleton('prometheus.registry', function () {
        return new CollectorRegistry(new ApcuAdapter());
    });
    

    Inject via constructor: public function __construct(private CollectorRegistry $registry).

  • Queue Job Metrics:

    $registry->getCounter('queue_jobs_total')->inc();
    $registry->getGauge('queue_job_duration_seconds')->set($duration);
    
  • Database Query Metrics: Use DB::listen() to track query counts/latency:

    DB::listen(function ($query) use ($registry) {
        $registry->getCounter('db_queries_total')->inc();
        $registry->getGauge('db_query_duration_seconds')->set($query->time);
    });
    

Gotchas and Tips

Pitfalls

  1. Storage Backend Quirks:

    • APCu/APC: Metrics are lost on server restart. Use Redis for persistence.
    • Redis: Ensure mget is supported (Redis ≥2.6). Fallback to individual get calls if needed:
      if (!method_exists($redis, 'mget')) {
          $registry->setStorage(new RedisAdapter($redis, false)); // Disable mget
      }
      
  2. Label Cardinality:

    • Avoid high-cardinality labels (e.g., user_id). Prometheus struggles with >100 unique label values per metric.
  3. Metric Naming:

    • Use underscores (api_requests_total), not camelCase. Prometheus expects snake_case.
  4. OPcache Dependencies:

    • The false check for opcache_get_status may log warnings if OPcache is disabled. Suppress with:
      error_reporting(E_ALL & ~E_NOTICE); // Temporarily disable notices
      
  5. Concurrency Issues:

    • Gauges/counters are not thread-safe. Use Laravel’s queue system for distributed updates:
      dispatch(new UpdateMetricsJob($registry, 'api_requests_total', 1));
      

Debugging

  • Metric Not Updating?:

    • Verify the metric exists: curl http://localhost/metrics | grep api_requests_total.
    • Check storage backend (e.g., Redis keys: KEYS *prometheus*).
  • High Memory Usage:

    • Redis mget can spike memory. Monitor with:
      redis-cli info memory
      
  • Prometheus Scrape Failures:

    • Ensure the /metrics endpoint returns 200 OK and valid Prometheus format:
      curl -I http://localhost/metrics
      

Extension Points

  1. Custom Storage: Implement StorageAdapterInterface for databases or other backends:

    class DatabaseAdapter implements StorageAdapterInterface {
        public function get($name) { /* ... */ }
        public function set($name, $value) { /* ... */ }
        public function delete($name) { /* ... */ }
    }
    
  2. Custom Formatters: Extend TextFormatter for JSON/Graphite output:

    class JsonFormatter extends TextFormatter {
        public function format($metrics) { /* ... */ }
        public function getMimeType() { return 'application/json'; }
    }
    
  3. Laravel Events: Hook into Illuminate\Queue\Events\JobProcessed or Illuminate\Http\KernelEvents:

    event(new JobProcessed($job));
    // In listener:
    $registry->getCounter('queue_jobs_total')->inc();
    
  4. Prometheus Rules: Define alerting rules in prometheus.rules.yml:

    groups:
    - name: laravel-alerts
      rules:
      - alert: HighAPILatency
        expr: api_latency_seconds > 1
        for: 5m
    
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