Sean Bannister Sean Bannister - 11 months ago 120
Node.js Question

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

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.


There's no built-in way to do this, but you can definitely add it yourself - here's how:

First, set up your logger like you normally would. For example:

var logger = new (winston.Logger)({
            "exitOnError" : true,
            "transports" : [
                new (winston.transports.Console)({ "colorize" : true, "level" : "silly", "silent" : false, "handleExceptions" : false }),

Then override the log() method (this is always called by the level methods - actually calls logger.log('foo').)

logger.log = function(){
  var args = arguments;
  if(args[2]) args[3] = args[2];
  args[2] = {
    "foo" : "bar"

All I'm doing above is making it so when logger.log() is called, it instead calls the above method, which adds the metadata (in this case, an object containing a foo key). Then it calls winston's Logger.log method from the proper context.

The above code would be in a module you create, at the bottom just export the logger:

module.exports = logger;

and import the logger module instead of the winston module in your sub classes.

var logger = require('./logger.js');

Hope that helps!