Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple Librato client for PHP
<?php
class LibratoClient
{
protected $user;
protected $token;
protected $metrics;
public function __construct($user, $token)
{
$this->user = $user;
$this->token = $token;
$this->resetMetrics();
}
public function __destruct()
{
$this->flush();
}
public function gauge($name, $value, array $opts = [])
{
$this->addMetric('gauges', $name, $value, $opts);
}
public function count($name, $value, array $opts = [])
{
$this->addMetric('counters', $name, $value, $opts);
}
public function addMetric($type, $name, $value, array $opts = [])
{
$this->metrics[$type][] = array_merge($opts, ['name' => $name, 'value' => $value]);
}
// flushes to librato server
public function flush()
{
$ch = curl_init("https://metrics-api.librato.com/v1/metrics");
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($this->metrics));
curl_setopt($ch, CURLOPT_USERPWD, sprintf("%s:%s", $this->user, $this->token));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
// TODO: $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$this->resetMetrics();
}
protected function resetMetrics()
{
$this->metrics = ['gauges' => [], 'counters' => []];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment