简体   繁体   English

如何在方法node.js中获取方法名称

[英]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. 因此,对上述方法的调用必须传递源文件,方法名称和行号,这可能在开发期间的任何时间点发生变化。

Eg 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? 问题 :是否更好地对所需的值进行硬编码(如上例所示),或者是否有任何方法可以在Node.js中以任何方式获取方法名称和行号?

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 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: 没有硬编码你的文件名是node.js中最容易实现的,没有第三方模块依赖:

var path = require('path');
var currentFile = path.basename(__filename); // where __filename always has the absolute path of the current file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM