本文介绍了获取日志输出的行号和文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以获取每个日志输出的行号和文件?
Is it possible to get the line number and file for each log output ?
例如:
var winston = require('winston');
winston.log('info', 'some message!'); // this is at line 4 of myfile.js
应在日志文件中指定某些消息"来自myFile.js第4行.
should specify in log file that 'some message' came from myFile.js line 4.
推荐答案
您可以将文件名传递为label
,并且可以从调用模块中获取文件名.
You can pass the file name as label
and you can get the file name from callingModule.
创建logger.js
文件和类似的代码
var winston = require('winston');
var getLabel = function (callingModule) {
var parts = callingModule.filename.split('/');
return parts[parts.length - 2] + '/' + parts.pop();
};
module.exports = function (callingModule) {
return new winston.Logger({
transports: [
new winston.transports.Console({
label: getLabel(callingModule),
json: false,
timestamp: true,
depth:true,
colorize:true
})
]
});
};
现在这是您的测试文件
var logger = require('./logger')(module);
function test() {
logger.info('test logger');
}
test();
如果您运行测试文件,则输出看起来像
and if you run test file than the output looks like
2017-07-08T07:15:20.671Z - info: [utils/test.js] test logger
这篇关于获取日志输出的行号和文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!