1

winston を使用してセルフロガーを作成しています。これにより、ログにタイムスタンプと行番号を追加できます。コードはそれぞれの機能を実現できますが、組み合わせると期待どおりに動作しません。

// **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);
}

ただし、行番号の構成が追加されると、ログのタイムスタンプは表示されなくなります。

たとえば、行番号構成を追加する前。

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

行番号構成を追加する場合

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

私が望む最適な結果は

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

これを修正できますか?

4

2 に答える 2

3

@ jeff-whitingの回答を更新し(クロージャーを使用して文字列補間を修正します)、単一の関数にしました。
既存のロガーを渡して、コールサイト情報をそのレベル関数に追加します。
注記logger.log()は変更されません。変更されるだけlogger.{level}()です。

// add callsite info to winston logger instance
function addCallSite(logger) {
  // WARNING: traceCaller is slow
  // http://stackoverflow.com/a/20431861/665507
  // http://stackoverflow.com/a/13411499/665507
  /**
  * examines the call stack and returns a string indicating
  * the file and line number of the n'th previous ancestor call.
  * this works in chrome, and should work in nodejs as well.
  *
  * @param n : int (default: n=1) - the number of calls to trace up the
  *   stack from the current call.  `n=0` gives you your current file/line.
  *  `n=1` gives the file/line that called you.
  */
  function traceCaller(n) {
    if( isNaN(n) || n<0) n=1;
    n+=1;
    var s = (new Error()).stack
      , a=s.indexOf('\n',5);
    while(n--) {
      a=s.indexOf('\n',a+1);
      if( a<0 ) { a=s.lastIndexOf('\n',s.length); break;}
    }
    b=s.indexOf('\n',a+1); if( b<0 ) b=s.length;
    a=Math.max(s.lastIndexOf(' ',b), s.lastIndexOf('/',b));
    b=s.lastIndexOf(':',b);
    s=s.substring(a+1,b);
    return s;
  }

  // assign to `logger.{level}()`
  for (var func in logger.levels) {
    (function (oldFunc) {
      logger[func] = function() {
        var args = Array.prototype.slice.call(arguments);
        if (typeof args[0] === 'string') {
          args[0] = traceCaller(1) + ' ' + args[0];
        }
        else {
          args.unshift(traceCaller(1));
        }
        oldFunc.apply(logger, args);
      };
    })(logger[func]);
  };
}
于 2014-09-12T18:13:29.080 に答える