add your own tokens to the patternLayout

This commit is contained in:
Jan Schmidle 2013-02-08 14:54:18 +01:00
parent 95568f352b
commit e4bf405f20
2 changed files with 38 additions and 9 deletions

View File

@ -10,8 +10,9 @@ var dateFormat = require('./date_format')
, "coloured": function() { return colouredLayout; }
, "pattern": function (config) {
var pattern = config.pattern || undefined;
return patternLayout(pattern);
}
var tokens = config.tokens || undefined;
return patternLayout(pattern, tokens);
}
}
, colours = {
ALL: "grey"
@ -143,9 +144,9 @@ function messagePassThroughLayout (loggingEvent) {
* Takes a pattern string and returns a layout function.
* @author Stephan Strittmatter
*/
function patternLayout (pattern) {
function patternLayout (pattern, tokens) {
var TTCC_CONVERSION_PATTERN = "%r %p %c - %m%n";
var regex = /%(-?[0-9]+)?(\.?[0-9]+)?([\[\]cdmnpr%])(\{([^\}]+)\})?|([^%]+)/;
var regex = /%(-?[0-9]+)?(\.?[0-9]+)?([\[\]cdmnprx%])(\{([^\}]+)\})?|([^%]+)/;
pattern = pattern || TTCC_CONVERSION_PATTERN;
@ -221,6 +222,17 @@ function patternLayout (pattern) {
case "%":
replacement = "%";
break;
case "x":
if(tokens[specifier]) {
if(typeof(tokens[specifier]) === 'function') {
replacement = tokens[specifier]();
} else {
replacement = tokens[specifier];
}
} else {
replacement = matchedString;
}
break;
default:
replacement = matchedString;
break;

View File

@ -4,9 +4,10 @@ assert = require('assert');
//used for patternLayout tests.
function test(args, pattern, value) {
var layout = args[0]
, event = args[1];
, event = args[1]
, tokens = args[2];
assert.equal(layout(pattern)(event), value);
assert.equal(layout(pattern, tokens)(event), value);
}
vows.describe('log4js layouts').addBatch({
@ -175,8 +176,12 @@ vows.describe('log4js layouts').addBatch({
level: {
toString: function() { return "DEBUG"; }
}
}, layout = require('../lib/layouts').patternLayout;
return [layout, event];
}, layout = require('../lib/layouts').patternLayout
, tokens = {
testString: 'testStringToken',
testFunction: function() { return 'testFunctionToken'; }
};
return [layout, event, tokens];
},
'should default to "time logLevel loggerName - message"': function(args) {
@ -246,6 +251,18 @@ vows.describe('log4js layouts').addBatch({
},
'%[%r%] should output colored time': function(args) {
test(args, '%[%r%]', '\033[36m14:18:30\033[39m');
}
},
'%x{testString} should output the string stored in tokens': function(args) {
test(args, '%x{testString}', 'testStringToken');
},
'%x{testFunction} should output the result of the function stored in tokens': function(args) {
test(args, '%x{testFunction}', 'testFunctionToken');
},
'%x{doesNotExist} should output the string stored in tokens': function(args) {
test(args, '%x{doesNotExist}', '%x{doesNotExist}');
},
'%x should output the string stored in tokens': function(args) {
test(args, '%x', '%x');
},
}
}).export(module);