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.
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.
To get the absolute path of the current file/code. To get the name of the file currently executing.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With