仅在开发模式Angular 2中console.log

时间:2018-09-03 08:46:49

标签: javascript angular console

我在console.log中有Angular 2 app条消息。我想在console.log中有dev,但不要在production中,所以我创建了Logger service,如下所示:

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 !!");
  }   

}

我对这种方法有疑问:

  • Dev中,所有从logger.service.ts文件中记录的消息都是正确的,但这使调试很难找到实际的记录位置(文件,行号)。 [就我而言,我有logger.service.ts文件,但在console中显示了另一个文件名]

    enter image description here

对此有何建议?

1 个答案:

答案 0 :(得分:2)

这种方法只是在控制台对象上添加了一层额外的内容,您需要在每个组件中注入logger服务,并使调试更加困难,但是您可以通过更改log,error,warm属性和冻结对象,使其变得不可更改

考虑这个

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);

}

这样,您可以正常使用控制台对象。