Got an old application, that prints out quite a lot of messages using console.log
, but I just can not find in which files and lines console.log
is called.
Is there a way to hook into the app and show file name and line numbers?
Steps to Open the Console Log in Google Chrome By default, the Inspect will open the "Elements" tab in the Developer Tools. Click on the "Console" tab which is to the right of "Elements". Now you can see the Console and any output that has been written to the Console log.
log() function from console class of Node. js is used to display the messages on the console. It prints to stdout with newline. Parameter: This function contains multiple parameters which are to be printed.
If you wish to add a new line to the JavaScript new line console while printing a few words, the \n sign for the new line can be used. JavaScript new line string manipulation is one of the things that is easy to learn, but difficult to master.
Having full stack trace for each call is a bit noisy. I've just improved the @noppa's solution to print only the initiator:
['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}`]); }; });
It also patches other methods (useful for Nodejs, since warn
and error
don't come with a stack trace as in Chrome).
So your console would look something like:
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With