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

Php Datadogstatsd Laravel Package

datadog/php-datadogstatsd

DogStatsD client for PHP from Datadog. Send metrics, events, and service checks to the Datadog Agent via UDP or UDS, with support for tags, sampling, buffering, and namespacing. Useful for instrumenting PHP apps and services.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require datadog/php-datadogstatsd
    

    Add to composer.json if using a custom package name (e.g., datadog/datadog-statsd).

  2. Basic Initialization

    use Datadog\Statsd\DogStatsd;
    
    $statsd = new DogStatsd([
        'host' => 'your-dogstatsd-host', // e.g., 'localhost' or 'statsd.example.com'
        'port' => 8125, // Default DogStatsd port
        'prefix' => 'myapp.', // Optional prefix for metrics
    ]);
    
  3. First Use Case: Incrementing a Counter

    $statsd->increment('user.signups'); // Tracks "user.signups" metric
    
  4. Where to Look First

    • README for config options.
    • src/DogStatsd.php for core methods (increment(), gauge(), histogram(), etc.).
    • src/Transport/UdpTransport.php for debugging connection issues and error handling.

Implementation Patterns

Core Workflows

  1. Metric Types

    • Counters: Track cumulative events (e.g., auth.failed).
      $statsd->increment('auth.failed');
      $statsd->decrement('auth.success');
      
    • Gauges: Track real-time values (e.g., queue.size).
      $statsd->gauge('queue.size', 42);
      
    • Timers/Histograms: Measure latency/duration.
      $statsd->timer('api.request', 150); // Milliseconds
      $statsd->histogram('api.response_size', 1024);
      
    • Sets: Track unique values (e.g., active_users).
      $statsd->set('active_users', ['user123', 'user456']);
      
  2. Tagging Metrics

    $statsd->increment('user.signups', 1, ['source' => 'web', 'region' => 'us-west']);
    
  3. Batching and Async

    • Enable async mode for high-throughput apps:
      $statsd = new DogStatsd([...], ['async' => true]);
      
    • Flush manually if needed:
      $statsd->flush();
      
  4. Integration with Laravel

    • Service Provider:
      // app/Providers/AppServiceProvider.php
      public function register()
      {
          $this->app->singleton(DogStatsd::class, function ($app) {
              return new DogStatsd([
                  'host' => config('datadog.statsd.host'),
                  'prefix' => config('datadog.statsd.prefix'),
              ]);
          });
      }
      
    • Middleware for Timing Requests:
      // app/Http/Middleware/LogRequestTime.php
      public function handle($request, Closure $next)
      {
          $start = microtime(true);
          $response = $next($request);
          $statsd = app(DogStatsd::class);
          $statsd->timer('http.request', (microtime(true) - $start) * 1000);
          return $response;
      }
      
  5. Error Handling

    • Wrap critical metrics in try-catch:
      try {
          $statsd->increment('critical.operation');
          // Risky operation...
      } catch (\Exception $e) {
          $statsd->increment('critical.operation.failed');
          throw $e;
      }
      

Gotchas and Tips

Pitfalls

  1. Connection Issues

    • Symptom: Metrics silently disappear.
    • Debugging:
      • Verify host/port in config (default: localhost:8125).
      • Check firewall/network policies (DogStatsd uses UDP).
      • New in 1.7.1: Define a custom error handler for socket errors:
        $statsd = new DogStatsd([...], [
            'errorHandler' => function (\Throwable $error) {
                \Log::error("DogStatsd socket error: " . $error->getMessage());
                // Optionally notify monitoring systems or retry logic
            }
        ]);
        
      • Enable logging in UdpTransport:
        $statsd = new DogStatsd([...], [
            'transport' => new \Datadog\Statsd\Transport\UdpTransport($socket, true)
        ]);
        
    • Fallback: Use a local buffer (e.g., Redis) if DogStatsd is unreliable.
  2. Metric Naming Collisions

    • Issue: Prefixes may not be applied as expected.
    • Fix: Explicitly set prefix and validate with:
      $statsd->setPrefix('app.'); // Ensure consistency
      
  3. Async Mode Quirks

    • Problem: Metrics may not appear immediately in Datadog.
    • Workaround: Call flush() before critical sections (e.g., app shutdown).
    • Note: Async mode is best for high-volume apps; disable for debugging.
  4. Sampling

    • DogStatsd drops metrics if the rate exceeds the server’s capacity.
    • Mitigation: Use lower-frequency metrics or increase DogStatsd’s maxPacketSize.
  5. Tag Limits

    • DogStatsd truncates tags after ~100 characters.
    • Tip: Use short, descriptive tags (e.g., env:prod instead of environment:production).

Debugging Tips

  1. Enable Verbose Logging

    $statsd = new DogStatsd([...], [
        'transport' => new \Datadog\Statsd\Transport\UdpTransport($socket, true, true) // Enable debug
    ]);
    
    • Logs will show raw UDP packets sent to DogStatsd.
  2. Test Locally with dd-agent

    • Run DogStatsd locally:
      docker run -p 8125:8125/udp datadog/agent:latest
      
    • Use nc -ul 8125 to inspect raw UDP traffic.
  3. Validate Metrics in Datadog

Extension Points

  1. Custom Transport

    • Implement Datadog\Statsd\Transport\TransportInterface for non-UDP backends (e.g., HTTP):
      class HttpTransport implements TransportInterface {
          public function send($data) {
              file_put_contents('http://statsd-endpoint', $data);
          }
      }
      
    • Pass to DogStatsd:
      $statsd = new DogStatsd([...], ['transport' => new HttpTransport()]);
      
  2. Custom Error Handling

    • New in 1.7.1: Define a custom error handler for socket errors to integrate with monitoring tools:
      $statsd = new DogStatsd([...], [
          'errorHandler' => function (\Throwable $error) {
              \Sentry\captureException($error); // Example: Send to Sentry
              // Or: \App\Services\Monitoring::alert($error);
          }
      ]);
      
    • This replaces the need for manual logging in UdpTransport for most use cases.
  3. Metric Sanitization

    • Override sanitizeMetricName() to enforce naming conventions:
      $statsd = new DogStatsd([...]);
      $statsd->sanitizeMetricName = function ($name) {
          return strtolower(preg_replace('/[^a-z0-9._]/', '_', $name));
      };
      
  4. Contextual Metrics

    • Attach request/user context to metrics:
      $statsd->increment('user.action', 1, [
          'user_id' => auth()->id(),
          'request_id' => request()->header('X-Request-ID'),
      ]);
      
  5. Rate Limiting

    • Throttle metrics to avoid overwhelming DogStatsd:
      $statsd->setRateLimit(1000); // Max 1000 metrics/sec
      
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky