TypeScript

Send custom metrics using TypeScript

Sending a metric via TCP

import * as net from 'net';

const socket = net.createConnection({ host: 'carbon.hostedgraphite.com', port: 2003 }, () => {
    socket.write('YOUR-API-KEY.foo.ts-tcp 1.2\n');
    socket.end();
});

Sending a metric via UDP

import * as dgram from 'dgram';

const socket = dgram.createSocket('udp4');

socket.send('YOUR-API-KEY.foo.ts-udp 1.2\n', 2003, 'carbon.hostedgraphite.com', () => {
    socket.close();
});

Sending a metric via HTTP POST

import * as https from 'https';

const apiKey = 'YOUR-API-KEY';
const metric = 'foo.ts-http';
const value = 1.2;

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

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

https.request({
    hostname: 'www.hostedgraphite.com',
    path: '/api/v1/sink',
    method: 'POST',
    headers: {
        'Content-Type': 'text/plain',
        'Content-Length': metricData.length,
        'Authorization': basicAuthHeader
    }
}, () => {}).end(metricData);

Sending a metric via StatsD

import * as dgram from 'dgram';

const socket = dgram.createSocket('udp4');

const apiKey = 'YOUR-API-KEY';
const metricName = 'test.testing-typescript-statsd';
const metricValue = 1.2;

const message = `${apiKey}.${metricName}:${metricValue}|<g/c/ms>`;

socket.send(message, 8125, 'statsd.hostedgraphite.com', () => {
    socket.close();
});

As with any TypeScript (.ts) file, compile it to JavaScript using tsc: tsc filename.ts and then execute the compiled script using Node.js: node filename.js.

Last updated