如何获取 Nodejs 中显示的 console.log 行号?

2024-04-03

有一个旧的应用程序,它使用以下命令打印出大量消息console.log,但我就是找不到哪些文件和行console.log叫做。

有没有办法连接到应用程序并显示文件名和行号?


每个调用都有完整的堆栈跟踪有点吵。我刚刚改进了 @noppa 的解决方案以仅打印启动器:

['log', 'warn', 'error'].forEach((methodName) => {
  const originalMethod = console[methodName];
  console[methodName] = (...args) => {
    let initiator = 'unknown place';
    try {
      throw new Error();
    } catch (e) {
      if (typeof e.stack === 'string') {
        let isFirst = true;
        for (const line of e.stack.split('\n')) {
          const matches = line.match(/^\s+at\s+(.*)/);
          if (matches) {
            if (!isFirst) { // first line - current function
                            // second line - caller (what we are looking for)
              initiator = matches[1];
              break;
            }
            isFirst = false;
          }
        }
      }
    }
    originalMethod.apply(console, [...args, '\n', `  at ${initiator}`]);
  };
});

它还修补其他方法(对于 Nodejs 很有用,因为warn and error不像 Chrome 那样带有堆栈跟踪)。

所以你的控制台看起来像这样:

Loading settings.json
   at fs.readdirSync.filter.forEach (.../settings.js:21:13)
Server is running on http://localhost:3000 or http://127.0.0.1:3000
   at Server.app.listen (.../index.js:67:11)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何获取 Nodejs 中显示的 console.log 行号? 的相关文章