Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to display the file Name in the log statement

Tags:

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:

Example : Below is the line executed from JobWork.js

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

Actual :

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

Required :

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

Without passing the fileName as a parameter from the log statement it should give the filename.

like image 226
Dexter Avatar asked Nov 16 '12 04:11

Dexter


People also ask

How do you name a log file in python?

If the logger is set with the GetLogger(name) option, where the name is a name that you specified you can also format the logger using %(name)s . You can specify a different name in every file with the GetLogger function, and when a log is produced you will know from which file comes through the name you set.

What is the purpose of __ filename variable?

To get the absolute path of the current file/code. To get the name of the file currently executing.


1 Answers

Looks like you're using Winston here - I typically pass module into my logger module and then set Winston's label property to a parsed version of module.filename. Something like:

logger.js:

const path = require('path');  // Return the last folder name in the path and the calling // module's filename. const getLabel = function(callingModule) {   const parts = callingModule.filename.split(path.sep);   return path.join(parts[parts.length - 2], parts.pop()); };  module.exports = function (callingModule) {   return new winston.Logger({     transports: [new winston.transports.Console({       label: getLabel(callingModule)     })]   }); }; 

Usage (assume module is controllers/users.js):

const logger = require('./logger')(module); logger.info('foo'); 

Result:

2014-11-25T15:31:12.186Z - info: [controllers/users.js] foo 
like image 54
ehynds Avatar answered Sep 23 '22 18:09

ehynds