简体   繁体   中英

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 :

  • In Dev all the message getting logged from logger.service.ts file which is correct but it making debugging hard to find actual logging place (file, line no). [ In my case I have logger.service.ts file but in console it showing another file name ]

    在此处输入图片说明

Any suggestion on this please ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM