Angular logger service. Wrapper for console log, will log only on development environment (production === false)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { isPlatformBrowser } from '@angular/common'; | |
import { Inject, Injectable, PLATFORM_ID } from '@angular/core'; | |
import { environment } from '../../environments/environment'; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class LoggerService { | |
constructor(@Inject(PLATFORM_ID) private platform: any) { | |
} | |
private buildMessage(message: [...any], wrapperFunction: string = 'log', origin: string = '', override: boolean = false) { | |
if (!environment.production || override) { | |
(console as any)[wrapperFunction](`[${wrapperFunction.toUpperCase()}] ${new Date().toISOString()} ${origin}: ${message}`); | |
} | |
} | |
log(message: [...any], origin: string = '', override: boolean = false) { | |
if (isPlatformBrowser(this.platform)) { | |
this.buildMessage(message, 'log', origin, override); | |
} | |
} | |
error(message: [...any], origin: string = '') { | |
this.buildMessage(message, 'error', origin, true); | |
} | |
debug(message: [...any], origin: string = '') { | |
if (isPlatformBrowser(this.platform)) { | |
this.buildMessage(message, 'debug', origin, !environment.production); | |
} | |
} | |
warn(message: [...any], origin: string = '', override: boolean = false) { | |
this.buildMessage(message, 'warn', origin, override); | |
} | |
logObject(object: any, origin: string = '', override: boolean = false) { | |
if (isPlatformBrowser(this.platform)) { | |
this.buildMessage([ JSON.stringify(object) ], 'log', origin, override); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment