3 May 2020

// // Leave a Comment

How to Remove console.log Messages From Any Application

Remove console log Messages


Being a developer often times we would find the need to write console log messages to debug the application that we write in JavaScript or any of it's frameworks.

More times that we can count, we tend to forget/ miss out removing the console statements that are written in our application. It could be either by one developer working on a small application or can be a team of developers working on a big application.

This post will help you suppress all the console log statements that are present in any application.

Let's take for example, that you have a JS file that performs some functionality in your application with some console log statements written in it. All you have to write is just a one liner at the top of the page.


window.console.log = function() {};


The above line would suppress all the console log statements and sent to a noop function that are written in your JS file. This can come very handy when you are pushing your files to production that will not print any console messages in your browser console.

This can even be written at your Node backend, if needed. Take this for example, you have a JS file that you are running in your node server by calling
node append.js


// File Name : append.js

function appendString(firstName, lastName) {
    console.log(`First Name is ${firstName}`);
    console.log(`Last Name is ${lastName}`);
    return `${firstName} ${lastName}`;
}

The above will print the two console log in your Node Terminal Console. So, to remove this, we will be adding a similar fix like the above to this append.js file.

Here's how it will look like


// File Name : append.js
console.log = function(){};
function appendString(firstName, lastName) {
    console.log(`First Name is ${firstName}`);
    console.log(`Last Name is ${lastName}`);
    return `${firstName} ${lastName}`;
}



We are not calling the window object here because that's not available at the server side. Window Object can be accessed at the client end.

We have to find one JS file that basically links all the other JS files in your application and write it on top of the file. This varies from application to application.

The above are just some simple examples, but I hope you get the idea as to where this line has to be put in your application.

For applications like Angular that has different environment setups, we can suppress the console logs specific to environments like only in production.

Here's how you can suppress the console log messages from an Angular Application. 
Drop your comments if this worked out for you or if there's a better way that you have found to do in your application.

Photo Credit. : Photo by Max Chen on Unsplash

0 comments:

Post a Comment