Programster's Blog

Tutorials focusing on Linux, programming, and open-source

Sending Metrics To Statsd With PHP

Someone has already created a popular PHP client library for interfacing with statsd that has over 1.5 million installs, so let's go ahead and pull that through composer.

composer require domnikl/statsd

Below is a simple script that will incerement a statistic. You might want run something like this on every request your web application gets so you can track how much traffic your sites are getting. It would also be a good idea to do it whenever your web application serves up any of the http error response codes, such as a 404.

<?php

require_once(__DIR__ . '/vendor/autoload.php');
define('GRAPHITE_SERVER_HOST', '10.2.0.70');
$connection = new \Domnikl\Statsd\Connection\UdpSocket(GRAPHITE_SERVER_HOST, 8125);
$statsd = new \Domnikl\Statsd\Client($connection, "test.namespace");

// the global namespace is prepended to every key (optional)
$statsd->setNamespace("test");

$statsd->increment("foo.bar");

Now if you execute that a couple of times and then head over to the your Graphite server you will be able to see the metrics by following the path shown.

As you can see, I executed the program 7 times at 19:40.

References

Last updated: 19th February 2020
First published: 16th August 2018

This blog is created by Stuart Page

I'm a freelance web developer and technology consultant based in Surrey, UK, with over 10 years experience in web development, DevOps, Linux Administration, and IT solutions.

Need support with your infrastructure or web services?

Get in touch