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.
Installation
composer require adgoal/statsd-php-client
Add to composer.json if using a custom package name.
Basic Initialization
use Adgoal\Statsd\Client;
$client = new Client('statsd.example.com', 8125);
First Use Case: Incrementing a Counter
$client->incr('user.signups', 1); // Track signups
Where to Look First
src/Client.php for core methods.tests/ for usage examples (if tests exist).Metrics Collection
$client->incr('api.requests', 1);
$client->decr('failed_jobs', 1);
$timer = $client->timer('db.query.time');
// ... execute query ...
$timer->stop(); // or use context manager
$client->gauge('queue.size', 42);
$client->set('active_users', ['user123', 'user456']);
Context Management
withTimer() for scoped timing:
$client->withTimer('user.profile.load', function () {
// Code block to time
});
Tagging (Custom Dimensions)
$client->incr('user.signups|region:eu|plan:premium', 1);
Batching
$client->setAutoFlush(false);
$client->incr('batch.metric', 100);
$client->flush(); // Manual send
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;
}
Logging Fallback
$client->setFallbackLogger(\Log::channel('statsd'));
No Built-in Connection Retries
Timer Precision
microtime(true), which may not be monotonic. For high-precision timing, consider hrtime().Tagging Limitations
statsd:user.signups,region:eu). Use pipe (|) separators manually:
$client->incr('user.signups|region:eu', 1);
Memory Leaks with Timers
stop() is called.No Async Support
Deprecated Methods
add() (use incr()/decr()). Check the source for other deprecated methods.Verify StatsD Server
telnet statsd.example.com 8125 or nc -z statsd.example.com 8125.Check Metrics in Backend
graphite-statsd or Prometheus to verify metrics are received. Example query:
stats.count(user.signups)
Enable Debug Logging
$client->setLogger(new \Monolog\Logger('statsd', [
new \Monolog\Handler\StreamHandler(storage_path('logs/statsd.log'))
]));
Common Issues
ping or mtr.Custom Host/Port
$client = new Client('custom.statsd.com', 8126, 'udp');
Protocol Selection
udp (default) or tcp. TCP is slower but reliable:
$client = new Client('statsd.example.com', 8125, 'tcp');
Namespace Prefixing
$client->setNamespace('app.');
$client->incr('user.signups'); // Sent as "app.user.signups"
Custom Metric Types
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");
}
}
Rate Limiting
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 { /* ... */ }
}
Dynamic Tagging
function tagMetric(Client $client, string $base, array $tags): void {
$tagged = implode('|', $tags);
$client->incr("{$base}|{$tagged}", 1);
}
How can I help you explore Laravel packages today?