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

domnikl/statsd-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require domnikl/statsd-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        Domnikl\StatsdBundle\DomniklStatsdBundle::class => ['all' => true],
    ];
    
  2. Configuration Define statsd in config/packages/domnikl_statsd.yaml:

    statsd:
        host: 'localhost'
        port: 8125
        prefix: 'myapp'
        sampling_rate: 1.0
    
  3. First Use Case Inject Statsd\Statsd into a service/controller:

    use Statsd\Statsd;
    
    class MyController extends AbstractController
    {
        public function __construct(private Statsd $statsd) {}
    
        public function index()
        {
            $this->statsd->increment('page.views');
            $this->statsd->timing('page.load', 150); // 150ms
        }
    }
    

Implementation Patterns

Common Workflows

  1. Metrics Collection

    • Timing: Measure execution time:
      $this->statsd->timing('db.query', $executionTimeMs);
      
    • Counters: Track events:
      $this->statsd->increment('user.signups');
      $this->statsd->decrement('failed.jobs');
      
    • Gauges: Track real-time values (e.g., queue size):
      $this->statsd->gauge('queue.size', count($queue));
      
  2. Contextual Metrics Use tags (via statsd client methods) for segmentation:

    $this->statsd->increment('api.calls', [], ['endpoint' => 'users', 'status' => '200']);
    
  3. Dependency Injection

    • Controllers: Autowire Statsd (as shown above).
    • Services: Use constructor injection:
      public function __construct(private Statsd $statsd) {}
      
    • Event Listeners: Inject via onKernelEvent:
      public function __construct(private Statsd $statsd) {}
      
      public function onKernelEvent(GetResponseEvent $event) {
          $this->statsd->increment('kernel.events');
      }
      
  4. Middleware Integration Track HTTP metrics in middleware:

    public function handle(Request $request, Closure $next): Response
    {
        $start = microtime(true);
        $response = $next($request);
        $this->statsd->timing('http.response', (microtime(true) - $start) * 1000);
        return $response;
    }
    
  5. Database Layer Wrap Doctrine queries with timing:

    $this->statsd->timing('db.query', function() use ($entityManager) {
        return $entityManager->createQuery('SELECT u FROM User u')->getResult();
    });
    

Gotchas and Tips

Pitfalls

  1. Sampling Rate

    • Default sampling_rate: 1.0 means 100% of metrics are sent. Adjust (e.g., 0.1 for 10%) to reduce load:
      sampling_rate: 0.1  # Send 10% of metrics
      
    • Tip: Use higher sampling for critical paths (e.g., 1.0 for /checkout).
  2. Prefix Collisions

    • Ensure prefix in config is unique (e.g., myapp.prod vs. myapp.dev).
    • Tip: Use environment variables:
      prefix: '%env(STATSD_PREFIX)%'
      
  3. Connection Issues

    • If StatsD server is unreachable, metrics are dropped silently. Add a fallback:
      try {
          $this->statsd->increment('critical.metric');
      } catch (\Exception $e) {
          // Log locally or use a backup (e.g., file-based)
          file_put_contents('/tmp/statsd_fallback.log', "Metric dropped: critical.metric\n", FILE_APPEND);
      }
      
  4. Tag Limits

    • StatsD has a 1500-byte limit for metric names + tags. Avoid long strings:
      // Bad: Exceeds limit
      $this->statsd->increment('user.profile.view', [], ['user_id' => '1234567890abcdef1234567890abcdef']);
      
      // Good: Shorten IDs or truncate
      $this->statsd->increment('user.profile.view', [], ['user_id' => '123456...']);
      
  5. Timing Granularity

    • StatsD expects milliseconds. Convert seconds to ms:
      $this->statsd->timing('process.time', $timeInSeconds * 1000);
      

Debugging

  1. Verify Metrics Use statsd CLI tools (e.g., graphite-statsd) or statsd-no-dogs to inspect metrics:

    statsd-no-dogs -p 8125 -l 0.0.0.0:8126
    

    Then visit http://localhost:8126 to see real-time metrics.

  2. Logging Enable debug mode in config/packages/domnikl_statsd.yaml:

    debug: true
    

    Logs will appear in Symfony’s dev.log.

  3. Network Issues Check if the StatsD server is running:

    telnet localhost 8125
    

    Or test with nc:

    echo "myapp.test:1|c" | nc localhost 8125
    

Extension Points

  1. Custom Metric Handlers Extend the bundle by creating a custom Statsd client:

    use Statsd\StatsdInterface;
    
    class CustomStatsd implements StatsdInterface
    {
        private $statsd;
    
        public function __construct(Statsd $statsd) {
            $this->statsd = $statsd;
        }
    
        public function customMetric(string $name, array $tags = [], array $data = []) {
            // Add custom logic (e.g., validation, transformation)
            $this->statsd->increment($name, $tags, $data);
        }
    }
    

    Register as a service:

    services:
        App\Service\CustomStatsd:
            arguments:
                $statsd: '@statsd'
    
  2. Async Metrics For high-throughput apps, use a queue (e.g., Symfony Messenger) to batch metrics:

    $this->messageBus->dispatch(new MetricMessage('api.calls', 1));
    

    Configure a handler to flush batches to StatsD.

  3. Dynamic Prefixes Override the prefix per environment or feature flag:

    $prefix = $this->featureFlagEnabled('new_metrics') ? 'myapp.v2' : 'myapp.v1';
    $this->statsd->setPrefix($prefix);
    
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.
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel
draftsmaninc/draftsman
square-bit/laravel-volition
himito/laravel-mailman
htinlynn/genius-helper
maco-studios/hephaestus
elmogy/larafast
xeviant/laravel-paystack
gorilladash/laravel-website-sdk
martialbe/flysystem-oss
chondal/3312client
jeroen-g/flickr
opscale-co/nova-genbi
itsjustvita/laravel-retention
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log