From 837d007de332c90a48e49adc8b19af6eeec4981c Mon Sep 17 00:00:00 2001 From: Karl Lam Date: Fri, 5 Jul 2013 11:23:59 +0800 Subject: [PATCH] GELF appender can add customFields to config for every message --- lib/appenders/gelf.js | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/lib/appenders/gelf.js b/lib/appenders/gelf.js index e3e2f5c..d8f264d 100644 --- a/lib/appenders/gelf.js +++ b/lib/appenders/gelf.js @@ -34,13 +34,16 @@ levelMapping[levels.FATAL] = LOG_CRIT; * @param hostname - hostname of the current host (default:os hostname) * @param facility - facility to log to (default:nodejs-server) */ -function gelfAppender (layout, host, port, hostname, facility) { +function gelfAppender (layout, host, port, hostname, facility, customFields) { host = host || 'localhost'; port = port || 12201; hostname = hostname || require('os').hostname(); facility = facility || 'nodejs-server'; layout = layout || layouts.messagePassThroughLayout; + + var defaultCustomFields = customFields || {}; + console.log(defaultCustomFields) var client = dgram.createSocket("udp4"); @@ -55,9 +58,22 @@ function gelfAppender (layout, host, port, hostname, facility) { * @param msg */ function addCustomFields(loggingEvent, msg){ + + /* append defaultCustomFields firsts */ + var keys = Object.keys(defaultCustomFields); + for (var i in keys){ + var key = keys[i]; + // skip _id field for graylog2, skip keys not starts with UNDERSCORE + if (!key.match(/^_/) || key === "_id") continue; + msg[key] = defaultCustomFields[key]; + } + + + /* append custom fields per message */ var data = loggingEvent.data; if (!Array.isArray(data) || data.length === 0) return; var firstData = data[0]; + if (!firstData['GELF']) return; // identify with GELF field defined var keys = Object.keys(firstData); for (var i in keys){ @@ -66,9 +82,9 @@ function gelfAppender (layout, host, port, hostname, facility) { if (!key.match(/^_/) || key === "_id") continue; msg[key] = firstData[key]; } - loggingEvent.data.shift(); // remove the first object - //console.log('=== msg ==='); - //console.log(msg); + + /* the custom field object should be removed, so it will not be looged by the later appenders */ + loggingEvent.data.shift(); } function preparePacket(loggingEvent) { @@ -112,7 +128,7 @@ function configure(config) { if (config.layout) { layout = layouts.layout(config.layout.type, config.layout); } - return gelfAppender(layout, config.host, config.port, config.hostname, config.facility); + return gelfAppender(layout, config.host, config.port, config.hostname, config.facility, config.customFields); } exports.appender = gelfAppender;