timestamps disappear when adding the line number configuration in node.js winston for logging

advertisements

I am using winston to make a self logger, which allow me to add the timestamps and line number in the logging. The code can accomplish the functionality each, but when combined, they don't work as expected.

// **help to add timestamp**
var logger = new (winston.Logger)({
  transports : [new (winston.transports.Console)({
    json : false,
    timestamp : true,
    colorize: true
  }), new winston.transports.File({
    filename : __dirname + '/debug.log',
    json : true
  })]
  ,exitOnError : false
});

// **help me to add line number**
var logger_info_old = winston.info;
logger.info = function(msg) {
    var fileAndLine = traceCaller(1);
    return logger_info_old.call(this, fileAndLine + ":" + msg);
}

However, when line number configuration is added, timestamp for the logging will disappear.

For example, before adding the line number configuration.

logger.info("abc");
2013-11-24T09:49:15.914Z - info:339:abc

when adding the line number configuration

logger.info("abc");
info: (H:\Dropbox\node\fablab\utils\logging.js:85:abc

The optimal result i want is like

logger.info("abc");
2013-11-24T09:49:15.914Z - info: (H:\Dropbox\node\fablab\app.js:339:abc

Can I fix this?


I got this to work and this is how I did it.

var transports = [
  new(winston.transports.Console)({
    colorize: true,
    prettyPrint: true,
    timestamp : true,
    level: 'debug',
  })
];

var log = new(winston.Logger)({
  "transports": transports
});

for (var func in winston.levels) {
  var oldFunc = log[func];

  log[func] = function() {
    var args = Array.prototype.slice.call(arguments);
    args.unshift(traceCaller(1));
    oldFunc.apply(log, args);
  }
}

With that I got both the timestamp and the file. (note traceCaller(1) is from this stackoverflow question: I want to display the file Name in the log statement). I did the for loop over the winston.levels so I would pickup all the functions not just info.

The reason yours didn't work was your logger_info_old was from winston and not from logger. So

var logger_info_old = winston.info;

should have been

var logger_info_old = logger.info;