3

why you should not use console.log( ) for debugging ?

 2 years ago
source link: https://dev.to/danyson/why-you-should-not-use-console-log-for-debugging-4pgg
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Node.js console.log and console.error

This built-in console module in Node.js lets you write log messages to stdout and stderr using the log and error functions.

It might appear simple and tempt you to use.

Lots of people prefer to use the console module.

But, this is not the best practice.

But why ?

Lets say, you want to debug or log a response from an API

app.js

const axios = require('axios');

 axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
    // do something with response data
  })
  .catch(function (error) {
    console.log(error);
    // do something with error
  });
Enter fullscreen modeExit fullscreen mode

Once you done with your debugging after developement phase, you need to remove the console.log() or comment it during production phase like follows.

app.js

const axios = require('axios');

 axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    // console.log(response); <----- line commented
    // do something with response data
  })
  .catch(function (error) {
    // console.log(error); <----- line commented
    // do something with error
  });
Enter fullscreen modeExit fullscreen mode

Now imagine a larger code base with 1000s of files.

Its a tedious process to comment and uncomment, right ?

Lets make debugging simple with The debug Module

Step 1

npm install debug --save

Now import and use the debug() replacing the console.log() or console.error() and set the environment variable as dev

app.js

const axios = require('axios');
var debug = require('debug')('dev') // dev is env variable

 axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    debug(response);
    // do something with response data
  })
  .catch(function (error) {
    debug(error);
    // do something with error
  });
Enter fullscreen modeExit fullscreen mode

Now run the code by setting the environment variable during Developement phase

$ DEBUG=dev node app.js

//response data or error will be printed

Enter fullscreen modeExit fullscreen mode

Simply, during Production phase remove environment variable and run code as follows

node app.js

// nothing gets printed
Enter fullscreen modeExit fullscreen mode

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK