How to get console.log line numbers in Nodejs?

console.logI got an old application that prints quite a lot of messages using , but I just can’t find which files and lines are being console.logcalled.

Is there a way to connect to the application and show the file name and line numbers?

+7
source share
3 answers

For a temporary hack to find the log operators you want to get rid of, it's not too hard to redefine console.logyourself.

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();
Run codeHide result

It will print something like

Foobar
Trace
at Console.console.log (index.js:4:13)
at foo (index.js:10:13)
at Object.<anonymous> (index.js:12:1)
...

It has a lot of noise, but the second line in the call stack at foo (index.js:10:13)should point to the right place.

+4
source

. @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 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)
+10

, Windows 10 ( 8.9.4), . , - :

Loading settings.json
   at fs.readdirSync.filter.forEach (D:\Users\Piyin\Projects\test\settings.js:21:13)
Server is running on http://localhost:3000 or http://127.0.0.1:3000
   at Server.app.listen (D:\Users\Piyin\Projects\test\index.js:67:11)

( ):

  • , - ( - " Error - , )
  • ( __dirname, D:\Users\Piyin\Projects\test). : , Javascript
  • Delete initial at
  • Put file information in front of the actual log
  • Format the information as Class.method at path/to/file:line:column

Here:

['log','warn','error'].forEach((methodName) => {
  const originalMethod = console[methodName];
  console[methodName] = (...args) => {
    try {
      throw new Error();
    } catch (error) {
      originalMethod.apply(
        console,
        [
          (
            error
            .stack // Grabs the stack trace
            .split('\n')[2] // Grabs third line
            .trim() // Removes spaces
            .substring(3) // Removes three first characters ("at ")
            .replace(__dirname, '') // Removes script folder path
            .replace(/\s\(./, ' at ') // Removes first parentheses and replaces it with " at "
            .replace(/\)/, '') // Removes last parentheses
          ),
          '\n',
          ...args
        ]
      );
    }
  };
});

And here is the new conclusion:

fs.readdirSync.filter.forEach at settings.js:21:13
 Loading settings.json
Server.app.listen at index.js:67:11
 Server is running on http://localhost:3000 or http://127.0.0.1:3000

Here is the code minimized by hand (240 bytes):

['log','warn','error'].forEach(a=>{let b=console[a];console[a]=(...c)=>{try{throw new Error}catch(d){b.apply(console,[d.stack.split('\n')[2].trim().substring(3).replace(__dirname,'').replace(/\s\(./,' at ').replace(/\)/,''),'\n',...c])}}});
0
source

Source: https://habr.com/ru/post/1682580/


All Articles