Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

add your own tokens to the patternLayout #113

Merged
merged 5 commits into from

3 participants

@bitcloud

Added the ability to add your own dynamic tokens to the patternLayout so you can easily extend your log with any additional information.

I currently use it to add the process pid to distinguish parallel running node instances logging to the same ressource.

I introduced a new %x field and used its specifier to address the token to use.

With this you should be able to add interesting status values like memory usage or any other status to your log messages to add some more context to them.

var log4js = require("log4js");

var config = {
    "appenders": [
      {
        "type": "console",
        "layout": {
          "type": "pattern",
          "pattern": "%[%r (%x{pid}) %p %c -%] %m%n",
          "tokens": {
            "pid" : function() { return process.pid; }
          }
        }
      }
    ]
  };

log4js.configure(config, {});

var logger = log4js.getLogger("app");
logger.info("Test log message");
@NicolasPelletier

Shouldn't you add the new %x in the function header documentation ? Maybe document new parameter 'tokens' as well.
PS> I cannot formally review your changes as I am just passing by to look at this module and not a user of log4js yet, but I just thought I'd mention it when I saw it. This seems an interesting addition.

@bitcloud

you are right, completely forgot about the documentation. Will work on that and submit another push.

@bitcloud

Don't know why af428c5 didn't go thru the test. There seems to be an error related to another part.

@nomiddlename nomiddlename merged commit 22da622 into nomiddlename:master

1 check passed

Details default The Travis build passed
@nomiddlename

Awesome - thanks a lot for this work, especially the attention to tests and documentation. Much appreciated.

@bitcloud bitcloud deleted the bitcloud:patternLayout_tokens branch
@nomiddlename

Released in 0.5.7 in npm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
This page is out of date. Refresh to see the latest.
View
21 examples/patternLayout-tokens.js
@@ -0,0 +1,21 @@
+var log4js = require('./lib/log4js');
+
+var config = {
+ "appenders": [
+ {
+ "type": "console",
+ "layout": {
+ "type": "pattern",
+ "pattern": "%[%r (%x{pid}) %p %c -%] %m%n",
+ "tokens": {
+ "pid" : function() { return process.pid; }
+ }
+ }
+ }
+ ]
+ };
+
+log4js.configure(config, {});
+
+var logger = log4js.getLogger("app");
+logger.info("Test log message");
View
35 lib/layouts.js
@@ -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"
@@ -139,13 +140,26 @@ function messagePassThroughLayout (loggingEvent) {
* - %d date in various formats
* - %% %
* - %n newline
+ * - %x{<tokenname>} add dynamic tokens to your log. Tokens are specified in the tokens parameter
* You can use %[ and %] to define a colored block.
- * Takes a pattern string and returns a layout function.
+ *
+ * Tokens are specified as simple key:value objects.
+ * The key represents the token name whereas the value can be a string or function
+ * which is called to extract the value to put in the log message. If token is not
+ * found, it doesn't replace the field.
+ *
+ * A sample token would be: { "pid" : function() { return process.pid; } }
+ *
+ * Takes a pattern string, array of tokens and returns a layout function.
+ * @param {String} Log format pattern String
+ * @param {object} map object of different tokens
+ * @return {Function}
* @author Stephan Strittmatter
+ * @author Jan Schmidle
*/
-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 +235,17 @@ function patternLayout (pattern) {
case "%":
replacement = "%";
break;
+ case "x":
+ if(typeof(tokens[specifier]) !== 'undefined') {
+ if(typeof(tokens[specifier]) === 'function') {
+ replacement = tokens[specifier]();
+ } else {
+ replacement = tokens[specifier];
+ }
+ } else {
+ replacement = matchedString;
+ }
+ break;
default:
replacement = matchedString;
break;
View
27 test/layouts-test.js
@@ -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);
Something went wrong with that request. Please try again.