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

Bri*_*unt 51 javascript node.js

如何获得调用当前函数的函数的名称和行?我希望有一个像这样的基本调试函数(使用npmlog定义log.debug):

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

当从另一个函数调用时,它将是这样的:

function hello() {
   debug("world!")
}
// outputs something like:
// "hello:2 'world!'"
Run Code Online (Sandbox Code Playgroud)

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

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

是否有一个节点等效于完成此操作?

Joe*_*Joe 72

使用此处的信息:访问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()
Run Code Online (Sandbox Code Playgroud)

分别返回'28'和'foo'.

  • 虽然这个解决方案很棒,但它很昂贵。我不会在生产代码中使用它。如果您使用 bunyan 记录器,您可以打开 [src 选项](https://github.com/trentm/node-bunyan#src)。但同样,他们也不建议在生产代码中使用该选项。我想要一个转译器,它可以在我运行我的代码之前用有关函数名称和行号的信息替换每个记录器调用。任何人?? (2认同)
  • 请注意,如果您使用严格模式,则由于“aguments.callee”,此方法将不起作用 (2认同)

Vik*_*ash 15

我也有类似的要求.我使用了nodejs提供的Error类的stack属性.
我仍在学习节点,因此可能存在错误的可能性.

以下是相同的解释.也创造了新公共管理模块一样,如果你喜欢,你可以检查:
1. NPM模块"logat"
2. 混帐回购协议

假设我们使用方法'log''记录'对象'

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

例:

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

输出上面的例子:

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


Bri*_*unt 13

我找到并安装了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'
};
Run Code Online (Sandbox Code Playgroud)


Cos*_*icu 9

以下代码仅使用核心元素。它从错误实例解析堆栈。

"use strict";
function debugLine(message) {
    let e = new Error();
    let frame = e.stack.split("\n")[2];
    let lineNumber = frame.split(":")[1];
    let functionName = frame.split(" ")[5];
    return functionName + ":" + lineNumber + " " + message;
}
function myCallingFunction() {
    console.log(debugLine("error_message"));
}
myCallingFunction();
Run Code Online (Sandbox Code Playgroud)

它输出类似 myCallingFunction:10 error_message

我已将错误的元素提取为变量(lineNumber,functionName),因此您可以按任意方式设置返回值的格式。

附带说明:该use strict;语句是可选的,仅当您的整个代码都使用严格标准时才可以使用。如果您的代码与此不兼容(尽管应该兼容),请随时将其删除。


Ale*_*hek 9

这是一个用于快速调试的单行代码:

console.log("DEBUG", (new Error().stack.split("at ")[1]).trim());
Run Code Online (Sandbox Code Playgroud)

这将使用 Node.js 记录如下内容:

调试 SomeObject.function (/path/to/the/code.js:152:37) 

——

您还可以在最后添加自定义参数,例如

DEBUG SomeObject.function (/path/to/the/code.js:152:37) 

请注意,如果您将其放入辅助函数中,请将堆栈索引从 eg 调整[1][2]