Skip to content

Instantly share code, notes, and snippets.

@mbrevoort
Created June 24, 2013 06:55
Show Gist options
  • Save mbrevoort/5848179 to your computer and use it in GitHub Desktop.
Save mbrevoort/5848179 to your computer and use it in GitHub Desktop.
A simple Logstash UDP logger for Winston.
// Really simple Winston Logstash UDP Logger
var dgram = require('dgram'),
util = require('util'),
os = require('os'),
winston = require('winston');
var LogstashUDP = module.exports = function (options) {
winston.Transport.call(this, options);
options = options || {};
this.name = 'logstashUdp';
this.localhost = options.localhost || os.hostname();
this.host = options.host || '127.0.0.1';
this.port = options.port || 9999;
this.application = options.appName || process.title;
this.pid = options.pid || process.pid;
this.client = dgram.createSocket("udp4");
};
util.inherits(LogstashUDP, winston.Transport);
LogstashUDP.prototype.log = function (level, msg, meta, callback) {
var self = this,
meta = winston.clone(meta || {});
if (self.silent) {
return callback(null, true);
}
var logEntry = {
"@message": msg,
"@source_host": self.localhost,
"@timestamp": new Date().toISOString(),
"@fields": {
"level": level,
"pid": self.pid,
"application": self.application
}
};
for (prop in meta) {
if (meta.hasOwnProperty(prop)) logEntry["@fields"][prop] = meta[prop];
}
self.sendLog(JSON.stringify(logEntry), callback);
};
LogstashUDP.prototype.sendLog = function (message, callback) {
var self = this;
callback = callback || function () {};
var buf = new Buffer(message)
self.client.send(buf, 0, buf.length, self.port, self.host, callback);
};
input {
udp {
format => "json_event"
port => 9999
type=> "app"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment