Skip to content

Instantly share code, notes, and snippets.

@alexbowers
Last active October 19, 2016 15:47
Show Gist options
  • Save alexbowers/e6cca0ffb2e010a1a13ef438dcba7f78 to your computer and use it in GitHub Desktop.
Save alexbowers/e6cca0ffb2e010a1a13ef438dcba7f78 to your computer and use it in GitHub Desktop.
Fire annotations into Grafana in PHP using UDP.

This is an annotation firing class.

You need to have InfluxDB setup to receive UDP connections.

An example config for influx is this:

[[udp]]
  enabled = true
  bind-address = ":8089"
  database = "events"
  precision = "s"

Feel free to change any of these values, but reflect them in the class above.

Usage:

new Annotation("Annotation Title");

You are required to passa title, but may optionally pass a message, which can contain HTML, an array of tags (which should not contain spaces), and a unix timestamp.

By default, the timestamp will be now; and no message or tags will be sent through.

Example:

new Annotation("Release v3.1.11", 'View the <a href="http://google.com/">Changelog</a>', ['Bug-Fix', 'Performance']);

In grafana it will appear like this:

image

<?php
class Annotation
{
private $ip = 'Your IP';
private $port = '8089';
/**
* Annotation constructor.
*
* @param $title
* @param null $message
* @param array $tags strings that do not contain spaces.
* @param null $timestamp Unix Epoch Timestamp | Defaults to now
*/
public function __construct($title, $message = null, array $tags = [], $timestamp = null)
{
$title = "title=\"{$title}\"";
if (!is_null($message)) {
$message = "text=\"{$message}\"";
}
if (!empty( $tags )) {
$tags = implode(' ', $tags);
$tags = "tags=\"{$tags}\"";
}
if (is_null($timestamp)) {
$timestamp = time();
}
$segments = [
$title,
$message,
$tags,
];
$segments = array_filter($segments);
$message = implode(',', $segments);
$message = "events {$message} {$timestamp}";
$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_sendto($socket, $message, strlen($message), 0, $this->ip, $this->port);
socket_close($socket);
}
}
@alexbowers
Copy link
Author

I will look into turning this into a simple composer package at some point, but for now this works well, Just add your own namespace and IP to the class.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment