Dipak Telangre
Dipak Telangre

Reputation: 1993

console.log only in development mode Angular 2

I have console.log messages in Angular 2 app. I want to have console.log in dev but not in production So I have created Logger service as below:

logger.service.ts

import { Injectable } from '@angular/core';
import { environment } from '../../../environments/environment';

@Injectable()
export class LoggerService {
  log(msg): void {
    if (!environment.production) {
      console.log(msg);
    }
  }
  error(msg): void {
    console.error(msg);
  }
  warn(msg, options): void {
    if (!environment.production) {
      if (options) console.warn(msg, options);
      else console.warn(msg);
    }
  }
} 

app.component.ts

import { Component, NgModule, OnInit } from '@angular/core';
import { environment } from '../environments/environment';   
import { LoggerService } from './shared/services/logger.service';

@Component({
  selector: 'web-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {    
  constructor(private _logger: LoggerService) {
    _logger.log("This is my test logger !!");
  }   

}

I have questions about this approach :

Any suggestion on this please ?

Upvotes: 1

Views: 1841

Answers (1)

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24406

This approach is just add an extra layer of delaing with console object and you need to inject the logger service in every component and make the debugging harder , but you can simply disable console object by change the log, error , warm property and freeze the object so it 's become unchangeable

consider this

main.ts

if (environment.production) {
  enableProdMode();

  let disFunc = () => 'console has been disabled in production mode';

  console.log = disFunc
  console.error = disFunc
  console.warn = disFunc

  Object.freeze(console);

}

this way you just use console object normally.

Upvotes: 3

Related Questions