Node.js

How to send custom metrics using Node.js

Sending a metric via TCP

var net = require("net");

var socket = net.createConnection(2003, "YOUR-UID.carbon.hostedgraphite.com", function() {
    socket.write("YOUR-API-KEY.foo.node-tcp 1.2\n");
    socket.end();
});

Sending a metric via UDP

// For Nodejs v10
var dgram = require("dgram");

var message = Buffer.from("YOUR-API-KEY.foo.node-udp 1.2\n")
var client = dgram.createSocket("udp4");
client.send(message, 0, message.length, 2003, "YOUR-UID.carbon.hostedgraphite.com", function(err, bytes) {
    client.close();
});

Sending a metric via StatsD

var dgram = require("dgram");

var message = Buffer.from("YOUR-API-KEY.foo.node-statsd:1.2|c\n")
var client = dgram.createSocket("udp4");
client.send(message, 0, message.length, 8125, "statsd.hostedgraphite.com", function(err, bytes) {
    client.close();
});

Sending a metric via HTTP POST

const http = require('http');

const apiKey = 'YOUR-API-KEY';
const metric = 'test.testing-node-http';
const value = 1.2;

const metricData = `${metric} ${value}`;

const basicAuthHeader = 'Basic ' + Buffer.from(apiKey).toString('base64');

const options = {
    hostname: 'www.hostedgraphite.com',
    path: '/api/v1/sink',
    method: 'POST',
    headers: {
        'Content-Type': 'text/plain',
        'Content-Length': Buffer.byteLength(metricData),
        'Authorization': basicAuthHeader
    }
};

const req = http.request(options, () => {});
req.write(metricData);
req.end();

Your API key can be found on your account home page.

Last updated