yaorg/node-measured

How to use this with Graphite?

Akuli opened this issue · 2 comments

Akuli commented

The README has a TODO about instructions for using this module with Graphite. Can someone tell me roughly how I should do this? I could then figure out the details and write nicer instructions. Thanks! :)

Akuli commented

In case someone else is wondering this too, I made this thing:

const net = require('net');
const os = require('os');
const stats = require('measured').createCollection();
const util = require('util');

function netcat(host, port, msg) {
  // this function is equivalent enough to this command:
  //   $ echo msg | nc host port
  // https://gist.github.com/tedmiston/5935757
  var client = new net.Socket();
  client.connect(port, host, function() {
    client.write(msg + "\n");
    client.destroy();
  });
  client.on('error', function(err) {
    console.error("sending data to graphite failed: " + err);
  });
}

setInterval(function() {
  // stats.toJSON() returns {} if stats.meter() hasn't been called yet
  const data = stats.toJSON().requestsPerSecond;
  const value = (data === undefined ? 0 : data.currentRate);

  // http://graphite.readthedocs.io/en/latest/feeding-carbon.html
  const timestamp = Math.floor(Date.now() / 1000);
  const msg = util.format(
    "nodeserver.%s.reqpersec %s %s", os.hostname(), value, timestamp);
  netcat('put the server IP here', 2003, msg);
}, 10000);

I'm sure there's a better way to do this without sockets, but this works well enough for me.