[英]console.log only in development mode Angular 2
I have console.log
messages in Angular 2 app
. 我在
Angular 2 app
有console.log
消息。 I want to have console.log
in dev
but not in production
So I have created Logger service
as below: 我想在
dev
人员中使用console.log
而不在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 !!");
}
}
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). 在
Dev
所有消息都是从logger.service.ts
文件中记录的,这是正确的,但它使调试很难找到实际的记录位置(文件,行号)。 [ In my case I have logger.service.ts
file but in console
it showing another file name ] [就我而言,我有
logger.service.ts
文件,但在console
显示了另一个文件名]
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 这种方法只是在控制台对象上添加了一层额外的内容,您需要在每个组件中注入logger服务,并使调试更加困难,但是您可以通过更改log,error,warm属性并冻结对象来禁用控制台对象所以它变得不可改变
consider this 考虑这个
main.ts 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. 这样,您只需正常使用控制台对象即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.