Disabling console.log() in production
Asked Answered
A

6

13

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.

Abstractionism answered 11/12, 2018 at 23:17 Comment(7)
Possible duplicate of How to quickly and conveniently disable all console.log statements in my code?Washtub
The suggestions there work for the chrome browser but not in IE 11 (the issue)Abstractionism
I just found this, seems relevant: beyondjava.net/…Washtub
I was hopeful but that doesn't seem to work for IE 11Abstractionism
@NathanielFlick - Apologies but I think the poly fiill in your console log surprises link worked!Abstractionism
no worries glad it worked!Washtub
devsuhas.com/2023/02/18/…Archambault
A
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(){}
 }
}
Abstractionism answered 12/12, 2018 at 14:48 Comment(2)
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.Ossicle
Thanks for the reminder @Deepak-MSFT, I had forgotten. Hopefully it does help someone in the future.Abstractionism
B
21

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

Boarfish answered 10/8, 2020 at 9:5 Comment(1)
thanks! I like this solution, other env should show the logs and this what I needed.Ciaphus
A
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(){}
 }
}
Abstractionism answered 12/12, 2018 at 14:48 Comment(2)
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.Ossicle
Thanks for the reminder @Deepak-MSFT, I had forgotten. Hopefully it does help someone in the future.Abstractionism
C
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.

Cheat answered 22/7, 2019 at 22:47 Comment(0)
E
1

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");
Extrajudicial answered 8/9, 2022 at 13:50 Comment(0)
M
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
Magnific answered 22/5, 2022 at 14:11 Comment(1)
When linking to your own site or content (or content that you are affiliated with), you must disclose your affiliation in the answer 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.Nacreous
D
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();
  }
}
Danger answered 29/8, 2023 at 20:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.