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

后端 未结 5 593
小蘑菇
小蘑菇 2020-12-02 20:54

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

5条回答
  •  [愿得一人]
    2020-12-02 21:39

    Slightly modified version of noppa's answer, this version will output something like:

    /file/in-which/console/is/called.js:75:23
     The stuff you want to log.
    

    This is clean and convenient (especially for use in VSCode - which will turn the file path into a link).

    const { log } = console;
    function proxiedLog(...args) {
      const line = (((new Error('log'))
        .stack.split('\n')[2] || '…')
        .match(/\(([^)]+)\)/) || [, 'not found'])[1];
      log.call(console, `${line}\n`, ...args);
    }
    console.info = proxiedLog;
    console.log = proxiedLog;
    
    // test
    console.log('Hello!');

    The snippet will only work well in a NodeJS environment…

提交回复
热议问题