Created
July 29, 2013 04:34
-
-
Save josegonzalez/6102163 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class StatsD { | |
// StastD::timing("www.php.sql_query", 645); | |
public static function __callStatic($name, $arguments) { | |
if (!in_array($name, array('counter', 'gauge', 'timing'))) { | |
throw new Exception("Invalid function"); | |
} | |
if (empty($arguments[0])) return false; | |
$stats = $arguments[0]; | |
$value = isset($arguments[1]) ? $arguments[1] : 0; | |
$types = array( | |
'counter' => 'c', | |
'gauge' => 'g', | |
'timing' => 'ms', | |
); | |
$data = array(); | |
foreach ((array)$stats as $stat) { | |
$data[$stat] = "{$value}|{$types[$name]}"; | |
} | |
StatsD::send($data, (isset($arguments[2]) ? $arguments[2] : 1)); | |
} | |
/* | |
* Send the metrics over UDP | |
**/ | |
public static function send($data, $samplerate=1) { | |
$host = defined('STATSD_HOST') ? STATSD_HOST : false; | |
$port = defined('STATSD_PORT') ? STATSD_PORT : false; | |
if (!($host && $port)) return; | |
$sampledData = $data; | |
// sampling | |
if ($samplerate < 1) { | |
$sampledData = array(); | |
foreach ($data as $stat => $value) { | |
if ((mt_rand() / mt_getrandmax()) <= $samplerate) { | |
$sampledData[$stat] = "{$value}|@{$samplerate}"; | |
} | |
} | |
} | |
if (empty($sampledData)) return; | |
// Wrap this in a try/catch - failures | |
// in any of this should be silently ignored | |
try { | |
$fp = fsockopen("udp://{$host}", $port, $errno, $errstr); | |
if (! $fp) return; | |
foreach ($sampledData as $stat => $value) { | |
fwrite($fp, "{$stat}:{$value}"); | |
} | |
fclose($fp); | |
return true; | |
} catch (Exception $e) { | |
return false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment