Disable Console.log in Production

cover-photo

Disable Console.log in Production



blog-photo

Disable Console log in Production

In this post we are gong to learn how to stop logging messages in Production Site. We all have seen that while we code in development we log certain messages for debugging purposes and often forget to remove it and it goes in production sites which is not something considerate.

So in Angular we create components and may use console.log() method to log messages in many of the components so we could write just one piece of code in app.component.ts and disable logging of messages from all components.

import { isDevMode } from '@angular/core';


ngOnInit() {
    if (!isDevMode()) {
        console.log = function () {};
    }
}

Here we have used the isDevMode() method provided by angular in @angular/core library. This method returns what is the project's environment.

This method returns value as true or false, that means if we are in development mode this method will return true and in production it will return as false.

So here we have assigned console.log() method an empty function() which will override the default mechanism of logging messages to browser's console and do nothing whenever console.log() method is called from any of the components.

Note: If we use isDevMode() make sure after this method enableProdMode() method is not used, which will enable your production environment's settings and isDevMode() method will return as false.

Tip: You could also use the Environment Variables provided by Angular to check for development and production Modes.

Check post Environment Variables it will explain how to use environment variables.

Hope you have understood how to stop logging messages in Angular's Production mode and use of isDevMode() method.


Happy Coding!