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

adgoal/statsd-php-client

Lightweight PHP client for StatsD metrics. Send counters, gauges, timers and other events to a StatsD server with minimal setup, suitable for adding application monitoring and performance tracking to Laravel or any PHP project.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require adgoal/statsd-php-client
    

    Add to composer.json if using a custom package name.

  2. Basic Initialization

    use Adgoal\Statsd\Client;
    
    $client = new Client('statsd.example.com', 8125);
    
  3. First Use Case: Incrementing a Counter

    $client->incr('user.signups', 1); // Track signups
    
  4. Where to Look First

    • Source Code (if available; verify URL)
    • src/Client.php for core methods.
    • tests/ for usage examples (if tests exist).

Implementation Patterns

Core Workflows

  1. Metrics Collection

    • Counters: Track discrete events.
      $client->incr('api.requests', 1);
      $client->decr('failed_jobs', 1);
      
    • Timers: Measure latency (auto-flushes on destruction).
      $timer = $client->timer('db.query.time');
      // ... execute query ...
      $timer->stop(); // or use context manager
      
    • Gauges: Track real-time values (e.g., queue size).
      $client->gauge('queue.size', 42);
      
    • Sets: Track unique values (e.g., active users).
      $client->set('active_users', ['user123', 'user456']);
      
  2. Context Management

    • Use withTimer() for scoped timing:
      $client->withTimer('user.profile.load', function () {
          // Code block to time
      });
      
  3. Tagging (Custom Dimensions)

    • Append tags to metrics (if supported by your StatsD backend):
      $client->incr('user.signups|region:eu|plan:premium', 1);
      
  4. Batching

    • Disable auto-flushing for bulk operations:
      $client->setAutoFlush(false);
      $client->incr('batch.metric', 100);
      $client->flush(); // Manual send
      
  5. Integration with Laravel

    • Service Provider:

      $this->app->singleton(Client::class, function ($app) {
          return new Client(config('statsd.host'), config('statsd.port'));
      });
      
    • Facade (optional):

      // app/StatsdFacade.php
      namespace App\Facades;
      use Adgoal\Statsd\Client;
      use Illuminate\Support\Facades\Facade;
      
      class StatsdFacade extends Facade {
          protected static function getFacadeAccessor() { return 'statsd'; }
      }
      

      Register in config/app.php under aliases.

    • Middleware for Timing Requests:

      public function handle($request, Closure $next) {
          $timer = app(Client::class)->timer('http.requests');
          $response = $next($request);
          $timer->stop();
          return $response;
      }
      
  6. Logging Fallback

    • If StatsD is down, log metrics to a fallback (e.g., Monolog):
      $client->setFallbackLogger(\Log::channel('statsd'));
      

Gotchas and Tips

Pitfalls

  1. No Built-in Connection Retries

    • The client does not retry failed UDP packets. Handle this in your app layer or use a queue.
  2. Timer Precision

    • Timers use microtime(true), which may not be monotonic. For high-precision timing, consider hrtime().
  3. Tagging Limitations

    • The package does not natively support structured tags (e.g., statsd:user.signups,region:eu). Use pipe (|) separators manually:
      $client->incr('user.signups|region:eu', 1);
      
  4. Memory Leaks with Timers

    • Unstopped timers (e.g., in exceptions) will leak memory. Use context managers or ensure stop() is called.
  5. No Async Support

    • UDP is fire-and-forget. If you need acknowledgments, implement a fallback (e.g., queue the metric and retry later).
  6. Deprecated Methods

    • Avoid add() (use incr()/decr()). Check the source for other deprecated methods.

Debugging

  1. Verify StatsD Server

    • Test connectivity with telnet statsd.example.com 8125 or nc -z statsd.example.com 8125.
  2. Check Metrics in Backend

    • Use tools like graphite-statsd or Prometheus to verify metrics are received. Example query:
      stats.count(user.signups)
      
  3. Enable Debug Logging

    • Temporarily log raw packets:
      $client->setLogger(new \Monolog\Logger('statsd', [
          new \Monolog\Handler\StreamHandler(storage_path('logs/statsd.log'))
      ]));
      
  4. Common Issues

    • Metrics Not Appearing: Ensure the StatsD server is running and the client is sending to the correct host/port.
    • High Latency: UDP packets may be dropped. Monitor with ping or mtr.
    • Negative Gauge Values: Gauges can go negative; handle business logic accordingly.

Configuration Quirks

  1. Custom Host/Port

    • Override defaults in the constructor:
      $client = new Client('custom.statsd.com', 8126, 'udp');
      
  2. Protocol Selection

    • Supports udp (default) or tcp. TCP is slower but reliable:
      $client = new Client('statsd.example.com', 8125, 'tcp');
      
  3. Namespace Prefixing

    • Prepend a namespace to all metrics:
      $client->setNamespace('app.');
      $client->incr('user.signups'); // Sent as "app.user.signups"
      

Extension Points

  1. Custom Metric Types

    • Extend the Client class to add custom metrics (e.g., histograms):
      class ExtendedClient extends Client {
          public function histogram($metric, $value) {
              $this->send("statsd.histogram:$metric:$value|h");
          }
      }
      
  2. Rate Limiting

    • Implement a decorator to throttle metric emission:
      class ThrottledClient {
          private $client;
          private $rateLimit;
      
          public function __construct(Client $client, int $rateLimit) {
              $this->client = $client;
              $this->rateLimit = $rateLimit;
          }
      
          public function incr($metric, $value = 1) {
              if ($this->canEmit()) {
                  $this->client->incr($metric, $value);
              }
          }
      
          private function canEmit(): bool { /* ... */ }
      }
      
  3. Dynamic Tagging

    • Create a helper to generate tagged metrics:
      function tagMetric(Client $client, string $base, array $tags): void {
          $tagged = implode('|', $tags);
          $client->incr("{$base}|{$tagged}", 1);
      }
      
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.
andydefer/laravel-notification
adachsoft/cli-process-tester
jhaskell13/laraflow
sebastienheyd/boilerplate-media-manager
ccast/tagixo-primix
pretendtrue/laravel-builder
sawmainek/laravel-scout-tntsearch-driver
tomshaw/laravel-calendar-table
dibakar/laravel-ownership
steadrun/laravel-monitor
labyrinthe/connect-laravel
elmogy/layan
drewdan/sentinel-client
dskripchenko/laravel-llm
fatryst/nuonuo
stevenay/myanfont
gmostafa/php-graphql-client
xeviant/paystack
snowsoft/faker
meditationsteps/blogetc