Layouts

Jan S edited this page Mar 22, 2017 · 8 revisions

Layout defines the way how a log record is rendered. log4js supports these layouts:

  • messagePassThrough
  • basic
  • colored
  • coloured
  • pattern

It can be set via layout.type property. Pattern layout also accepts custom pattern string, that may include specifiers:

  • %r - time in toLocaleTimeString format
  • %p - log level
  • %c - log category
  • %h - hostname
  • %z - process id
  • %m - log data
  • %d - date in various formats
  • %% - %
  • %n - newline
  • %x{<tokenname>} - add dynamic tokens to your log. Tokens are specified in the tokens parameter
  • %[ and %] - define a colored bloc

Here is an example configuration:

{
  appenders: [
    {
      type: 'console',
      layout: {
        type: 'pattern',
        pattern: "[%r] [%[%5.5p%]] - %m%n"
      }
    }
  ]
}

That yields log messages like this:

[15:43:49] [ INFO] - foo

And another example using ISO8601 time, left justified level with color, category, and no extra new line:

{
  appenders: [
    {
      type: 'console',
      layout: {
        type: 'pattern',
        pattern: "%d{ABSOLUTE} %[%-5p%] %c %m"
      }
    }
  ]
}

That yields log messages like this:

13:24:04.776 INFO  - MyCategory foo
13:24:04.778 ERROR - MyCategory bar

An example using a custom token to report the namespace, file and line of the logging event. Note the $depth variable is fragile, depending on the size of the call stack, which depends on the version of Log4js you are using. For this reason, I suggest we path layouts.js to include this useful (but time consuming) feature.

var $depth = 11;
var config = {
    appenders: [{
        type: "console",
        layout: {
            type    : "pattern",
            pattern : "%[%p {%x{ln}} -%]\t%m",
            tokens: {
                ln : function() {
                    // The caller:
                    return (new Error).stack.split("\n")[$depth]
                    // Just the namespace, filename, line:
                    .replace(/^\s+at\s+(\S+)\s\((.+?)([^\/]+):(\d+):\d+\)$/, function (){
                        return arguments[1] +' '+ arguments[3] +' line '+ arguments[4];
                        // return arguments[0] +' '+ arguments[2] +' line '+arguments[3]
                    });
                }
            }
        }
    }]
};

That yields log messages like this:

INFO {Runner.<anonymous> spec.js line 61} -     ✓ should load
DEBUG {Importer.module.exports.repopulate Importer.js line 89} -    PATH:  torrents.csv

Date formats

Following date format specifiers are currently supported:

  • %d{ISO8601}
  • %d{ISO8601_WITH_TZ_OFFSET}
  • %d{ABSOLUTE}
  • %d{DATE}