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

dbstudios/prometheus-client-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require dbstudios/prometheus-client-bundle
    

    For Symfony Flex projects, the bundle auto-enables. Otherwise, add to config/bundles.php:

    DaybreakStudios\PrometheusClientBundle\DaybreakStudiosPrometheusClientBundle::class => ['all' => true],
    
  2. Basic Configuration Place this in config/packages/dbstudios_prometheus.yaml (Symfony 4+) or app/config/config.yml (Symfony 3.4-):

    dbstudios_prometheus:
        adapter: DaybreakStudios\PrometheusClient\Adapter\ApcuAdapter
    

    Note: The ApcuAdapter is memory-based and requires APCu installed. For production, consider RedisAdapter or FileAdapter.

  3. First Metric Inject the PrometheusClient service and register a counter:

    use DaybreakStudios\PrometheusClient\PrometheusClient;
    
    class MyController extends AbstractController
    {
        public function __construct(private PrometheusClient $prometheus)
        {
        }
    
        public function index()
        {
            $counter = $this->prometheus->getCounter('my_app_requests_total', 'Total requests');
            $counter->inc();
            // ...
        }
    }
    
  4. Expose Metrics Add this route to your config/routes.yaml:

    prometheus:
        path: /metrics
        controller: DaybreakStudios\PrometheusClientBundle\Controller\MetricsController::metrics
    

    Access /metrics to see Prometheus-compatible metrics.


Implementation Patterns

Core Workflows

1. Metric Registration and Usage

  • Counters (e.g., request counts, errors):
    $counter = $prometheus->getCounter('app_errors_total', 'Total HTTP errors', ['status_code']);
    $counter->inc(1, ['status_code' => '500']);
    
  • Gauges (e.g., active connections, memory usage):
    $gauge = $prometheus->getGauge('active_users', 'Current active users');
    $gauge->inc(5); // or $gauge->dec(2);
    
  • Histograms (e.g., request latency):
    $histogram = $prometheus->getHistogram('request_latency_seconds', 'Request latency', ['route']);
    $histogram->observe(0.456, ['route' => 'homepage']);
    
  • Summaries (e.g., percentiles):
    $summary = $prometheus->getSummary('api_latency_seconds', 'API latency', ['endpoint']);
    $summary->observe(0.123, ['endpoint' => 'users']);
    

2. Contextual Metrics with Labels

Use labels to segment metrics (e.g., by user, route, or environment):

$counter = $prometheus->getCounter('user_actions', 'User actions', ['user_id', 'action']);
$counter->inc(1, ['user_id' => '123', 'action' => 'login']);

3. Middleware for Automatic Metrics

Create middleware to track requests globally:

namespace App\Middleware;

use DaybreakStudios\PrometheusClient\PrometheusClient;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;

class PrometheusMiddleware implements MiddlewareInterface
{
    public function __construct(private PrometheusClient $prometheus) {}

    public function handle(Request $request, HttpKernelInterface $next)
    {
        $start = microtime(true);
        $response = $next->handle($request);
        $duration = microtime(true) - $start;

        $this->prometheus->getHistogram('http_request_duration_seconds')
            ->observe($duration, ['method' => $request->getMethod(), 'path' => $request->getPathInfo()]);

        return $response;
    }
}

Register in config/services.yaml:

services:
    App\Middleware\PrometheusMiddleware:
        tags:
            - { name: kernel.middleware, priority: -100 }

4. Custom Adapters for Production

For distributed systems, replace the default ApcuAdapter with a shared adapter (e.g., Redis):

# config/packages/dbstudios_prometheus.yaml
dbstudios_prometheus:
    adapter: redis_adapter

Define the Redis adapter service:

services:
    redis_adapter:
        class: DaybreakStudios\PrometheusClient\Adapter\RedisAdapter
        arguments:
            - '@redis.client'

5. Scheduled Scraping

Use Symfony’s Cron component or a scheduler to scrape metrics periodically:

# config/packages/monolog.yaml (example with Monolog)
monolog:
    handlers:
        prometheus:
            type: stream
            path: php://output
            level: debug
            process_psr_3_messages: false
            formatter: monolog.formatter.json

Combine with a cron job to push metrics to Prometheus.


Integration Tips

Laravel-Specific Adaptations

Since this is a Symfony bundle, use Symfony’s Bridge in Laravel:

  1. Install Symfony components:
    composer require symfony/http-foundation symfony/dependency-injection symfony/config
    
  2. Bootstrap Symfony’s DI container in Laravel’s AppServiceProvider:
    use Symfony\Component\DependencyInjection\ContainerBuilder;
    
    public function boot()
    {
        $container = new ContainerBuilder();
        $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../config'));
        $loader->load('dbstudios_prometheus.yaml');
        $this->app->singleton('prometheus', function () use ($container) {
            return $container->get('DaybreakStudios\PrometheusClient\PrometheusClient');
        });
    }
    

Prometheus Alerting

Define rules in prometheus.rules:

groups:
- name: app-alerts
  rules:
  - alert: HighErrorRate
    expr: rate(app_errors_total[1m]) > 0.1
    for: 5m
    labels:
      severity: critical
    annotations:
      summary: "High error rate on {{ $labels.instance }}"

Visualization with Grafana

  1. Add Prometheus as a data source in Grafana.
  2. Create dashboards for:
    • Request rates (rate(http_request_duration_seconds_count[1m])).
    • Error trends (increase(app_errors_total[5m])).
    • Latency percentiles (histogram_quantile(0.95, sum(rate(http_request_duration_seconds_bucket[1m])) by (le))).

Gotchas and Tips

Pitfalls

1. Adapter Mismatches

  • Issue: Using ApcuAdapter in production without APCu installed causes crashes.
  • Fix: Always validate the adapter’s dependencies. For Docker, ensure:
    RUN docker-php-ext-install apcu
    
  • Alternative: Use FileAdapter for local testing (metrics stored in /tmp/prometheus).

2. Label Cardinality Explosion

  • Issue: Overusing labels (e.g., user_id) can bloat metrics.
  • Fix: Limit labels to high-level dimensions (e.g., user_type, region). Use le (bucket) labels for histograms.

3. Metric Naming Collisions

  • Issue: Reusing metric names across services can corrupt data.
  • Fix: Prefix metrics with your app name (e.g., laravel_app_requests_total).

4. Memory Leaks with ApcuAdapter

  • Issue: APCu has a memory limit; unbounded metrics can fill it.
  • Fix: Set apc.enable_cli=0 in php.ini or use RedisAdapter for shared environments.

5. Symfony/Laravel Dependency Conflicts

  • Issue: Mixing Symfony and Laravel DI containers may cause service resolution errors.
  • Fix: Explicitly bind the PrometheusClient to Laravel’s container:
    $this->app->bind('DaybreakStudios\PrometheusClient\PrometheusClient', function ($app) {
        return $app->make('prometheus'); // Your custom service
    });
    

Debugging

1. Verify Metrics Endpoint

  • Check /metrics returns valid Prometheus format:
    curl http://localhost/metrics | grep ^#
    
  • Expected output:
    # HELP my_app_requests_total Total requests
    # TYPE my_app_requests_total counter
    my_app_requests_total 42
    

2. Log Adapter Issues

Enable debug mode in

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.
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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