我想在日志语句中显示文件名 [英] I want to display the file Name in the log statement
问题描述
对于任何级别的每个logger语句,我需要显示执行log语句的文件名,下面是我在下面给出的插图:
For every logger statement with any level, I need to display the file name from where the log statement executed, below is the illustration I given below:
示例: 下面是从 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
在不从日志语句中传递fileName作为参数的情况下,它应该提供文件名.
Without passing the fileName as a parameter from the log statement it should give the filename.
推荐答案
您可以使用附加到v8的Error
对象的堆栈跟踪信息来查找调用代码的文件/行.这种方法行之有效,但效果不佳.因此,如果您在开发过程中使用它,则在生产时将要禁用它.
You can use the stack trace information attached to v8's Error
object to find out what file/line your code was called from. This approach works well, but it does not perform well; so if you use it during development, you will want to disable it when you go to production.
因此您可以执行以下操作:
So you could do something like this:
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;
}
这篇关于我想在日志语句中显示文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!