Skip to content

Instantly share code, notes, and snippets.

@ericmustin
Created January 28, 2020 15:52
Show Gist options
  • Save ericmustin/84846722da01dbae5719e3adbff7ff98 to your computer and use it in GitHub Desktop.
Save ericmustin/84846722da01dbae5719e3adbff7ff98 to your computer and use it in GitHub Desktop.
example statsd callback in node

setup and usage

  • download folder
  • cd into root
  • npm install
  • node index.js

Sample Output

COMP10929:statsd_example eric.mustin$ node index.js
Successfully sent 20 bytes
var StatsD = require('./test_client.js'),
var client = new StatsD({
host: 'localhost',
port: 8125,
tags: { env: 'dev' },
protocol: "udp"
});
client.flush("some example message", function(error, bytes) {
//this only gets called once after all messages have been sent
if(error){
console.error('Oh noes! There was an error:', error);
} else {
console.log('Successfully sent', bytes, 'bytes');
}
})
{
"name": "statsd_example",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"hot-shots": "^6.8.5",
"safe-buffer": "^5.2.0"
}
}
const dgram = require('dgram')
const lookup = require('dns').lookup // cache to avoid instrumentation
const Buffer = require('safe-buffer').Buffer
const MAX_BUFFER_SIZE = 1024 // limit from the agent
class Client {
constructor (options) {
options = options || {}
this._host = options.host || 'localhost'
this._port = options.port || 8125
this._prefix = options.prefix || ''
this._tags = options.tags || []
this._queue = []
this._buffer = ''
this._offset = 0
this._udp4 = dgram.createSocket('udp4')
this._udp6 = dgram.createSocket('udp6')
}
flush (input, callback) {
lookup(this._host, (err, address, family) => {
if (err === null) {
this._send(address, family, Buffer.from(input.toString(), 'utf-8'), callback)
}
})
}
_send (address, family, buffer, callback) {
const socket = family === 6 ? this._udp6 : this._udp4
socket.send(buffer, 0, buffer.length, this._port, address, callback)
}
}
module.exports = Client
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment