我想在日志语句中显示文件名

Dex*_*ter 17 logging node.js winston

对于任何级别的每个logger语句,我需要显示执行日志语句的文件名,下面是我在下面给出的插图:

示例:下面是从JobWork.js执行的行

logger.info("getInCompleteJobs in job works");
Run Code Online (Sandbox Code Playgroud)

实际:

2012-11-05T06:07:19.158Z - info: getInCompleteJobs in job works
Run Code Online (Sandbox Code Playgroud)

要求:

2012-11-05T06:07:19.158Z - info JobWork.js : getInCompleteJobs in job works
Run Code Online (Sandbox Code Playgroud)

如果不将fileName作为日志语句中的参数传递,则应该给出文件名.

ehy*_*nds 32

看起来你在这里使用Winston - 我通常会module进入我的记录器模块,然后将Winston的label属性设置为解析版本module.filename.就像是:

logger.js:

const path = require('path');

// Return the last folder name in the path and the calling
// module's filename.
const getLabel = function(callingModule) {
  const parts = callingModule.filename.split(path.sep);
  return path.join(parts[parts.length - 2], parts.pop());
};

module.exports = function (callingModule) {
  return new winston.Logger({
    transports: [new winston.transports.Console({
      label: getLabel(callingModule)
    })]
  });
};
Run Code Online (Sandbox Code Playgroud)

用法(假设模块是controllers/users.js):

const logger = require('./logger')(module);
logger.info('foo');
Run Code Online (Sandbox Code Playgroud)

结果:

2014-11-25T15:31:12.186Z - info: [controllers/users.js] foo
Run Code Online (Sandbox Code Playgroud)

  • 这是我试过的所有其他的很酷,但你怎么得到行号? (2认同)
  • 与@UalterJr的评论相关. - 您可以使用Node的[path.sep](https://nodejs.org/api/path.html#path_path_sep)获取可移植代码:`const path = require('path'); ... var parts = callingModule.filename.split(path.sep)` (2认同)

Lee*_*Lee 15

您可以使用附加到v8 Error对象的堆栈跟踪信息来查找调用代码的文件/行.这种方法效果很好,但效果不佳; 因此,如果您在开发过程中使用它,则需要在开始生产时禁用它.

所以你可以这样做:

  var logger_info_old = logger.info;
  logger.info = function(msg) {
    var fileAndLine = traceCaller(1);
    return logger_info_old.call(this, fileAndLine + ":" + msg);
  }

  /**
  * 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;
  }
Run Code Online (Sandbox Code Playgroud)

  • 为什么`b`是全球性的? (3认同)