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

有一个旧的应用程序,打印出相当多的消息使用console.log ,但我只是无法find哪些文件和行console.log被调用。

有没有办法挂钩到应用程序,并显示文件名和行号?

对于一个临时的黑客来find你想摆脱的日志语句,自己重写console.log并不是很难。

 var log = console.log; console.log = function() { log.apply(console, arguments); // Print the stack trace console.trace(); }; // Somewhere else... function foo(){ console.log('Foobar'); } foo(); 

每次通话都有完整的堆栈跟踪,有点吵。 我刚刚改进了@ noppa的解决scheme,只打印启动器:

 ['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有用,因为warnerror不像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)