Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get console.log line numbers shown in Nodejs?

Tags:

node.js

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?

like image 652
AngeloC Avatar asked Jul 30 '17 00:07

AngeloC


People also ask

How do I check output of console log?

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.

Can you console log in node js?

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.

How do you add a line in console log?

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.


1 Answers

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) 
like image 116
Dmitry Druganov Avatar answered Oct 04 '22 06:10

Dmitry Druganov