Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get line number and filename for a log output

Is it possible to get the line number and file for each log output ?

For example:

  var winston = require('winston');

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

should specify in log file that 'some message' came from myFile.js line 4.

like image 972
Lev Avatar asked Jul 06 '17 15:07

Lev


1 Answers

You can pass the file name as label and you can get the file name from callingModule.

Create logger.js file and code like

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
            })
        ]
    });
};

Now Here your test file

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
like image 117
Nitin Avatar answered Oct 06 '22 03:10

Nitin