Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular console log only on development environment

Tags:

angular

In our Angular app (made with Angular CLI) we use several console statements. Is there a global way to detect environment and then display console.log in our components and service only under development?

What I mean by global way - I know we can use something like:

if (!environment.production) {   console.log(this.reviewTasksList); } 

But by using this code everytime we have to console.log (along with necessary import to get environment variable) our code will become kind of verbose.

I want to know if there is a way to maybe:

  • access the environment in a quicker way
  • Maybe delete all console logs at prod build time

Or the better solution here is to create a logger service and do all the environment check within it?

I don't want my bundle size to be impacted by debug statements and service.

like image 861
BlackHoleGalaxy Avatar asked Apr 27 '17 11:04

BlackHoleGalaxy


People also ask

Can I use console log in Angular?

Programmers frequently use console. log to record errors or other informational messages in their Angular applications. Although this is fine while debugging your application, it's not a best practice for production applications.

Does Angular build Remove console log?

This doesn't strip console. log. It simply changes console.

What is logging service in Angular?

AngularJs includes logging service $log, which logs the messages to the browser's console. The $log service includes different methods to log the error, information, warning or debug information. It can be useful in debugging and auditing.


1 Answers

This overwrites all console logs with blank function.

if (environment.production) {   enableProdMode();   window.console.log = function () { };   // disable any console.log debugging statements in production mode   // window.console.error = function () { };  } 
like image 145
Taranjit Kang Avatar answered Sep 21 '22 12:09

Taranjit Kang