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

Statsd Laravel Package

domnikl/statsd

PHP client library for StatsD, providing a simple API to send counters, timers, gauges and other metrics. Supports batching and multiple transports (UDP/TCP) to help instrument applications and report performance and usage data to StatsD-compatible servers.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require domnikl/statsd
    

    Add to config/app.php under providers:

    Domnikl\Statsd\StatsdServiceProvider::class,
    

    Publish config (optional):

    php artisan vendor:publish --provider="Domnikl\Statsd\StatsdServiceProvider"
    

    Update .env with your StatsD server details (e.g., STATSD_HOST=localhost, STATSD_PORT=8125).

  2. First Use Case Inject the Statsd facade or service into a controller/service:

    use Domnikl\Statsd\Facades\Statsd;
    
    public function trackUserActivity()
    {
        Statsd::increment('user.activity'); // Track a counter
        Statsd::timing('user.activity.latency', 150); // Record latency in ms
    }
    
  3. Key Config Check config/statsd.php for:

    • host, port, prefix (default: app.)
    • flush_interval (default: 1000 ms)
    • flush_timeout (default: 500 ms)

Implementation Patterns

Core Workflows

  1. Metrics Collection

    • Counters: Track discrete events (e.g., Statsd::increment('api.requests')).
    • Timers: Measure durations (e.g., Statsd::timing('db.query', 42)).
    • Gauges: Record real-time values (e.g., Statsd::gauge('memory.usage', 1024)).
    • Sets: Track unique values (e.g., Statsd::set('active.users', ['user1', 'user2'])).
  2. Middleware Integration Use middleware to auto-track HTTP metrics:

    namespace App\Http\Middleware;
    
    use Closure;
    use Domnikl\Statsd\Facades\Statsd;
    
    class StatsdMiddleware
    {
        public function handle($request, Closure $next)
        {
            Statsd::timing('http.request', fn() => $next($request)->getContent());
        }
    }
    
  3. Service Integration Wrap database queries or external API calls:

    Statsd::timing('service.external_api', function() {
        return Http::get('https://api.example.com/data');
    });
    
  4. Batch Processing Use flush() explicitly for critical metrics:

    Statsd::increment('batch.processed');
    // ... process 1000 items ...
    Statsd::flush(); // Force sync to StatsD server
    
  5. Custom Prefixes Override the global prefix per context:

    Statsd::setPrefix('feature.x.');
    Statsd::increment('feature.x.usage');
    

Gotchas and Tips

Pitfalls

  1. Connection Issues

    • Symptom: Metrics silently disappear.
    • Fix: Verify STATSD_HOST/PORT in .env and check firewall/network policies.
    • Debug: Enable logging in config/statsd.php:
      'log_errors' => true,
      
  2. Prefix Collisions

    • Issue: Overlapping prefixes (e.g., app. + feature.) can clutter dashboards.
    • Solution: Use consistent naming (e.g., app.feature.x.) or disable global prefix:
      Statsd::setPrefix('');
      
  3. Timer Granularity

    • Gotcha: Timers use milliseconds. Pass microtime(true) for sub-millisecond precision:
      $start = microtime(true);
      // ... operation ...
      Statsd::timing('operation.time', (microtime(true) - $start) * 1000);
      
  4. Flush Behavior

    • Warning: Auto-flush runs every flush_interval (default: 1s). For high-volume apps, reduce flush_interval or call flush() manually.
    • Tradeoff: Smaller intervals increase network overhead.
  5. Gauge Updates

    • Caveat: Gauges require absolute values (not deltas). Incorrect usage:
      // WRONG: Treats as delta
      Statsd::gauge('memory.usage', +512);
      // RIGHT: Set absolute value
      Statsd::gauge('memory.usage', 1536);
      

Debugging Tips

  1. Enable Debug Mode

    Statsd::debug(true); // Logs all metric calls to stderr
    
  2. Check UDP Packets Use tcpdump to verify packets reach StatsD:

    tcpdump -i any -n udp port 8125
    
  3. Test Locally Run StatsD locally with Graphite:

    docker run -p 8125:8125/udp -p 80:80 grafana/statsd
    

    Access metrics at http://localhost.

Extension Points

  1. Custom Backends Extend Domnikl\Statsd\Statsd to support alternative transports (e.g., HTTP):

    class HttpStatsd extends Statsd
    {
        protected function send($data)
        {
            Http::post('https://stats.example.com', ['data' => $data]);
        }
    }
    
  2. Metric Sanitization Override sanitizeMetricName() to enforce naming conventions:

    Statsd::setSanitizer(function($name) {
        return preg_replace('/[^a-zA-Z0-9._-]/', '_', $name);
    });
    
  3. Contextual Tagging Use Statsd::tag() to add context (requires StatsD v0.7+):

    Statsd::tag('environment', 'production');
    Statsd::increment('user.signups');
    
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.
ilhamsyabani/laravel-volt-starter
thethunderturner/filament-latex
ghostcompiler/laravel-querybuilder
webrek/laravel-telescope-mongodb
anousss007/blatui
zatona-eg/zatona-eg-api
cocosmos/filament-sticky-save-bar
patrickbussmann/oauth2-apple
3brs/enterprise-security-bundle
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
daikazu/eloquent-salesforce-objects
unseen-codes/chat