Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a method name inside a method node.js

Scenario: Consider I am having multiple methods doing different tasks and handled by different developers. I am trying to make a generic method call which logs if error occurs. So the need is I have to log a Line No, Method name, etc..

I wrote a generic function, as follows:

  function enterLog(sourcefile, methodName, LineNo)
    {
            fs.appendFile('errlog.txt', sourcefile +'\t'+ methodName +'\t'+ LineNo +'\n', function(e){
            if(e)
                console.log('Error Logger Failed in Appending File! ' + e);
        });
    }

So, the call for the above method has to pass source file, method name and the Line No. Which may change at any point of time during development.

E.g. for calling method with hard-coded values:

enterLog('hardcodedFileName.js', 'TestMethod()', '27');

Question: Is it better to hard-code the values (as above example) required or is there any way to get the method name & line no reference from any way in Node.js?

like image 644
Amol M Kulkarni Avatar asked May 23 '13 11:05

Amol M Kulkarni


1 Answers

there is a nice module out there which we use in our applications-logger. you can even fetch the line number. https://npmjs.org/package/traceback

so you could rewrite it like that:

var traceback = require('traceback');

function enterLog(sourcefile, methodName, LineNo) {
  var tb = traceback()[1]; // 1 because 0 should be your enterLog-Function itself
  fs.appendFile('errlog.txt', tb.file +'\t'+ tb.method +'\t'+ tb.line +'\n', function(e) {
    if(e) {
      console.log('Error Logger Failed in Appending File! ' + e);
    }
  });
}

and just call:

enterLog();

from wherever you want and always get the correct results

Edit: another hint. not hardcoding your filename is the easiest to achieve in node.js without 3rd-party-module-dependencies:

var path = require('path');
var currentFile = path.basename(__filename); // where __filename always has the absolute path of the current file
like image 161
hereandnow78 Avatar answered Sep 22 '22 13:09

hereandnow78