Node.js: Winston: Can I add default meta data to all log messages

Sean Bannister picture Sean Bannister · Feb 21, 2012 · Viewed 32.2k times · Source

I'm using Winston in Node.js for logging. I know I can add metadata individually to each log message but is there a way to specify a default set of metadata that'll be added to every log message (such as the app name) as I don't want to specify it every time I need to send a log message.

Answer

DrakaSAN picture DrakaSAN · Aug 17, 2016

For Winston v2 (see comments)

There are now rewriters.

For example, the below will add a property app to every metadata going through this logger.

    logger.rewriters.push(function(level, msg, meta) {
      meta.app = 'myApp';
      return meta;
    });

You can also declare it when building the logger:

    new (winston.Logger)({
            level: config.log[file].level,
            rewriters: [
                (level, msg, meta) => {
                    meta.app = 'myApp';
                    return meta;
                }
            ],
            transports: [
                /*your transports*/
            ]
    });