一尘不染

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

node.js

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

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

logger.info("getInCompleteJobs in job works");

实际:

2012-11-05T06:07:19.158Z - info: getInCompleteJobs in job works

必填:

2012-11-05T06:07:19.158Z - info JobWork.js : getInCompleteJobs in job works

如果不通过log语句传递fileName作为参数,则应提供文件名。


阅读 202

收藏
2020-07-07

共1个答案

一尘不染

您可以使用附加到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;
  }
2020-07-07