Reputation: 1993
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 ?
Upvotes: 1
Views: 1841
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