This content originally appeared on DEV Community and was authored by Danyson
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
});
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
});
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
});
Now run the code by setting the environment variable during Developement phase
$ DEBUG=dev node app.js
//response data or error will be printed
Simply, during Production phase
remove environment variable and run code as follows
node app.js
// nothing gets printed
This content originally appeared on DEV Community and was authored by Danyson
Danyson | Sciencx (2021-08-14T21:07:37+00:00) why you should not use console.log( ) for debugging ?. Retrieved from https://www.scien.cx/2021/08/14/why-you-should-not-use-console-log-for-debugging/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.