11

I have run the following to disable console logs for production environments in my angular application. The below code works as expected for chrome, however, it still shows logs in IE 11.

main.ts

if (environment.production) {
  enableProdMode();
if(window){
  window.console.log=function(){};
 }
}

Is this a polyfill issue? I wasn't able to find anything online about it.

EDIT

This question may seem similar but does not address my issue as to why overriding the console log function to a blank method works in chrome but not IE 11.

R2B Boondocks
  • 394
  • 1
  • 2
  • 16

6 Answers6

20

The question has been answered and the answer has been accepted, but I want to show you a better way to disable/switch-off console.log in production. under src/envirenmonts add an environment.ts with the following content:

export const environment = {
  production: false,

  mode: 'Dev'
} 

In the main.ts import the envirenmont const:

import './polyfills';
...
import { environment } from './environments/environment';

Now add the following code-snippet:

..

if (environment.production) {
      window.console.log = () => { }
}

platformBrowserDynamic().bootstrapModule(AppModule).then(ref => {
  ...
}).catch(err => console.error(err)); 

To try this, add a console.log in the constructor of the app.component.ts:

...
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  ...
  constructor() {    
    console.log('How to switch off logging in Production?')
  }
}

Switch the environment.production to true/false to see the result Here is a working stackblitz

Meziane
  • 1,586
  • 1
  • 12
  • 22
14

Solution is to add the polyfill to your polyfill.ts file

if(!window.console) {
 var console = {
  log : function(){},
  warn : function(){},
  error : function(){},
  time : function(){},
  timeEnd : function(){}
 }
}
R2B Boondocks
  • 394
  • 1
  • 2
  • 16
  • 1
    From your last post, I can see that your issue is solved now and you had posted the solution. I suggest you to mark that solution as an accepted answer for this question after 24 hrs may help other community members in future in similar kind of issues. Thanks for your understanding. – Deepak-MSFT Dec 13 '18 at 01:13
  • Thanks for the reminder @Deepak-MSFT, I had forgotten. Hopefully it does help someone in the future. – R2B Boondocks Dec 14 '18 at 02:21
1

I have added a custom log function in Utility.ts class as follows

    public static log(strValue: string) {
    if (CoreService._env !== 'prod') {
      console.log(strValue);
    }
  }

Where _env variable defined in CoreService and assigned value inside app. component as follows

this.coreService.env = environment.env;

In environment.ts file define env as follows

export const environment = { env: 'dev'} // for production it will be 'prod'

And my component is using

Utility.log("Print the value");

That way, you can easily prevent logs on production.

Hkachhia
  • 4,463
  • 6
  • 41
  • 76
Sandeep
  • 499
  • 4
  • 12
0

I have cretated a little library for issues like this: deblog. You don't have to rewrite the console object methods.

You can create a wrapper of the console object and define proper methods for logging that you can configure as you wish and disable them for production:

For instance, you can do something like this:

import { createDeblog } from "deblog";

const configuration = {
  logs: [
    {
      name: "foo",
      level: "debug",
      tag: "FOO -",
      enabled: true,  // <- THIS can be set using a PRODUCTION_LOG variable set to "false"
    },
    {
      name: "bar",
      level: "log",
      tag: `[${new Date(Date.now()).toLocaleTimeString()}] BAR -`,
    },
  ],
};

let dlog = createDeblog(configuration);

dlog.disableAllBut("bar"); // Silencing all logs but bar

dlog.foo("1 Connection Error"); // Will not be logged
dlog.bar("I'm here!");
dlog.foo("2 Connection Error"); // Will not be logged
dlog.bar("I just need bar logs here");

dlog.restoreAll();

dlog.bar("4 Connection Error"); // Will be logged
msalafia
  • 2,703
  • 5
  • 23
  • 34
  • When linking to your own site or content (or content that you are affiliated with), you [must disclose your affiliation _in the answer_](/help/promotion) in order for it not to be considered spam. Having the same text in your username as the URL or mentioning it in your profile is not considered sufficient disclosure under Stack Exchange policy. The answer also needs to contain more information than *just* a link to your content, e.g. you could add usage information to the answer. Please update all the recent answers you've posted that link to your content like this. – cigien May 22 '22 at 19:05
0

This solution for works for all Angualr, ReactJS, VueJS and Vanilla JavaScript etc.

You can enable / disable by this way!

console.log("Before disabled logs");

const consoleLog = false

if(!consoleLog) {
  console.log = function() {} 
}

console.log("After disabled logs #1");
console.log("After disabled logs #2");
GMKHussain
  • 3,342
  • 1
  • 21
  • 19
0
    import { Injectable } from '@angular/core';
    import { environment } from 'src/environments/environment';
     
    @Injectable({ providedIn: 'root' }) 
    
    export class ConsoleToggleService { 
       constructor() {}
    
       disableConsoleInProduction(): void { 
         if (environment.production) {
           console.warn(` Console output is disabled on production!`);
           console.log = function (): void { };
           console.debug = function (): void { };
           console.warn = function (): void { };
           console.info = function (): void { };
         }
       }
    }

Finally, in your AppComponent, inject the ConsoleToggleService and call the disableConsoleInProduction() function in the constructor, like this:

export class AppComponent {
  constructor(private consoleToggleService: ConsoleToggleService) {
     this.consoleToggleService.disableConsoleInProduction();
  }
}
Ndiaga GUEYE
  • 191
  • 3
  • 7