在node.js中获取调用函数的名字和行

怎样才能得到一个叫做当前函数的函数的名字和行? 我想有一个这样的基本的debuggingfunction(用npmlog定义log.debug ):

 function debug() { var callee, line; /* MAGIC */ log.debug(callee + ":" + line, arguments) } 

当从另一个函数调用它会是这样的:

 function hello() { debug("world!") } // outputs something like: // "hello:2 'world!'" 

为了清楚起见,我想要的基本上类似于Python中的这个 :

 import inspect def caller(): return inspect.stack()[2][3] // line no from getframeinfo().lineno 

有一个节点相当于完成这个?

使用这里的信息: 访问V8 JavaScript中的行号(Chrome&Node.js)

你可以添加一些原型来提供从V8获取这些信息:

 Object.defineProperty(global, '__stack', { get: function() { var orig = Error.prepareStackTrace; Error.prepareStackTrace = function(_, stack) { return stack; }; var err = new Error; Error.captureStackTrace(err, arguments.callee); var stack = err.stack; Error.prepareStackTrace = orig; return stack; } }); Object.defineProperty(global, '__line', { get: function() { return __stack[1].getLineNumber(); } }); Object.defineProperty(global, '__function', { get: function() { return __stack[1].getFunctionName(); } }); function foo() { console.log(__line); console.log(__function); } foo() 

分别返回“28”和“foo”。

我find并安装了node-stack-trace模块(使用npm install stack-trace ),然后将echo定义为:

 function echo() { var args, file, frame, line, method; args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; frame = stackTrace.get()[1]; file = path.basename(frame.getFileName()); line = frame.getLineNumber(); method = frame.getFunctionName(); args.unshift("" + file + ":" + line + " in " + method + "()"); return log.info.apply(log, args); // changed 'debug' to canonical npmlog 'info' }; 

我也有类似的要求。 我使用了nodejs提供的Error类的堆栈属性。
所以我还在学习节点,可能有错误的机会。

以下是对相同的解释。 同样也创build了npm模块,如果你喜欢的话,可以查看:
1. npm模块'logat'
2. git回购

假设我们用方法'log'logging对象

 var logger = { log: log } function log(msg){ let logLineDetails = ((new Error().stack).split("at ")[3]).trim(); console.log('DEBUG', new Date().toUTCString(), logLineDetails, msg); } 

例:

 //suppose file name: /home/vikash/example/age.js function getAge(age) { logger.log('Inside getAge function'); //suppose line no: 9 } 

上面的输出示例:

  DEBUG on Sat, 24 Sept 2016 12:12:10 GMT at getAge(/home/vikash/example/age.js:9:12) Inside getAge function