diff --git a/lib/rotatingfilestream.js b/lib/rotatingfilestream.js index 503511d..e347b07 100644 --- a/lib/rotatingfilestream.js +++ b/lib/rotatingfilestream.js @@ -31,15 +31,52 @@ function RotatingFileStream(options) { var stream = null; var streambytesWritten = 0; + function nullJsonify(textlog) { + return textlog; + } + + function fastJsonify(rawlog) { + return JSON.stringify(rawlog, bunyan.safeCycles()) + '\n'; + } + + function orderedJsonify(rawlog) { + var log = {}; + + for (var fieldsortindex = 0; options.fieldOrder && fieldsortindex < options.fieldOrder.length; fieldsortindex += 1) { + if (rawlog.hasOwnProperty(options.fieldOrder[fieldsortindex])) { + log[options.fieldOrder[fieldsortindex]] = rawlog[options.fieldOrder[fieldsortindex]]; + } + } + + for (var k in rawlog) { + log[k] = rawlog[k]; + } + + return JSON.stringify(log, bunyan.safeCycles()) + '\n'; + } + + function chooseJsonify(log) { + if (typeof (log) === 'string' && options.fieldOrder) { + base.emit('error', 'Can only set fieldOrder with the stream set to "raw"'); + } + + if (typeof (log) === 'string') { + jsonify = nullJsonify; + } else if (options.fieldOrder) { + jsonify = orderedJsonify; + } else { + jsonify = fastJsonify; + } + + return jsonify(log); + }; + + var jsonify = chooseJsonify; + var forceWrite = false; function writer(logs, callback) { for (var i = 0; stream && i < logs.length; i += 1) { - var str; - if (typeof (logs[i]) === 'string') { - str = logs[i]; - } else { - str = JSON.stringify(logs[i], bunyan.safeCycles()) + '\n'; - } + var str = jsonify(logs[i]); var writeBuffer = new Buffer(str, 'utf8');