diff --git a/lib/layouts.js b/lib/layouts.js index 320d12c..c0a8cc2 100644 --- a/lib/layouts.js +++ b/lib/layouts.js @@ -24,37 +24,19 @@ var dateFormat = require('./date_format') , OFF: "grey" }; -function formatLogData(logData) { - var output = "" - , data = Array.isArray(logData) ? logData.slice() : Array.prototype.slice.call(arguments) - , format = data.shift(); - - if (typeof format === "string") { - output = format.replace(replacementRegExp, function(match) { - switch (match) { - case "%s": return new String(data.shift()); - case "%d": return new Number(data.shift()); - case "%j": return JSON.stringify(data.shift()); - default: - return match; - }; - }); +function wrapErrorsWithInspect(items) { + return items.map(function(item) { + if ((item instanceof Error) && item.stack) { + return { inspect: function() { return util.format(item) + '\n' + item.stack; } }; } else { - //put it back, it's not a format string - data.unshift(format); + return item; } + }); +} - data.forEach(function (item) { - if (output) { - output += ' '; - } - output += util.inspect(item); - if (item && item.stack) { - output += "\n" + item.stack; - } - }); - - return output; +function formatLogData(logData) { + var data = Array.isArray(logData) ? logData : Array.prototype.slice.call(arguments); + return util.format.apply(util, wrapErrorsWithInspect(data)); } var styles = { diff --git a/test/layouts-test.js b/test/layouts-test.js index 105fd1c..26a3786 100644 --- a/test/layouts-test.js +++ b/test/layouts-test.js @@ -64,7 +64,7 @@ vows.describe('log4js layouts').addBatch({ colour: "green" , toString: function() { return "ERROR"; } } - }), "thing 1 'cheese'"); + }), "thing 1 cheese"); }, 'should output the first item even if it is not a string': function(layout) { assert.equal(layout({ @@ -89,21 +89,20 @@ vows.describe('log4js layouts').addBatch({ }).match(/Error\s+at Object\..*\s+\((.*)test[\\\/]layouts-test\.js\:\d+\:\d+\)\s+at runTest/) , 'regexp did not return a match'); }, - 'with passed augmented errors': - { topic: - function(layout){ - var e = new Error("My Unique Error Message"); - e.augmented = "My Unique attribute value" - e.augObj = { at1: "at2" } - return layout({ - data: [ e ] - , startTime: new Date(2010, 11, 5, 14, 18, 30, 45) - , categoryName: "cheese" - , level: { - colour: "green" - , toString: function() { return "ERROR"; } - } - }); + 'with passed augmented errors': { + topic: function(layout){ + var e = new Error("My Unique Error Message"); + e.augmented = "My Unique attribute value" + e.augObj = { at1: "at2" } + return layout({ + data: [ e ] + , startTime: new Date(2010, 11, 5, 14, 18, 30, 45) + , categoryName: "cheese" + , level: { + colour: "green" + , toString: function() { return "ERROR"; } + } + }); }, 'should print error the contained error message': function(layoutOutput) { var m = layoutOutput.match(/\{ \[Error: My Unique Error Message\]/);