获取日志输出的行号和文件名

Lev*_*Lev 6 logging node.js winston

是否可以获取每个日志输出的行号和文件?

例如:

  var winston = require('winston');

  winston.log('info', 'some message!'); // this is at line 4 of myfile.js
Run Code Online (Sandbox Code Playgroud)

应该在日志文件中指定'some message'来自myFile.js第4行.

Nit*_*iya 9

您可以传递文件名label,您可以从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
            })
        ]
    });
};
Run Code Online (Sandbox Code Playgroud)

现在这里是你的测试文件

var logger = require('./logger')(module);
function test() {
    logger.info('test logger');
}
test();
Run Code Online (Sandbox Code Playgroud)

如果你运行测试文件比输出看起来像

2017-07-08T07:15:20.671Z - info: [utils/test.js] test logger
Run Code Online (Sandbox Code Playgroud)