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

danyson

Danyson

Posted on August 14, 2021

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

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 mode Exit 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 mode Exit 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 mode Exit 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 mode Exit fullscreen mode

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

node app.js

// nothing gets printed
Enter fullscreen mode Exit fullscreen mode

Support Us on Buy Me a Coffee

💖 💪 🙅 🚩
danyson
Danyson

Posted on August 14, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related