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

后端 未结 5 599
小蘑菇
小蘑菇 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:33

    I found Dmitry Druganov's answer really nice, but I tried it on Windows 10 (with Node 8.9.4) and it didn't work well. It was printing the full path, something like:

    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)
    

    So I took said answer and made these improvements (from my point of view):

    • Assume the important line of the stack trace is the third one (the first one is the word Error and the second one is where you place this script)
    • Remove the current script folder path (given by __dirname, which in my case is D:\Users\Piyin\Projects\test). Note: For this to work well, the script should be on the project's main Javascript
    • Remove the starting at
    • Place the file information before the actual log
    • Format the information as Class.method at path/to/file:line:column

    Here it is:

    ['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's the new output:

    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's the minified-by-hand code (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])}}});
    

提交回复
热议问题