Skip to content

Instantly share code, notes, and snippets.

@jsanta
Created March 21, 2022 14:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsanta/95a58f9d452be61c26c40eb1e4c2e5a9 to your computer and use it in GitHub Desktop.
Save jsanta/95a58f9d452be61c26c40eb1e4c2e5a9 to your computer and use it in GitHub Desktop.
Angular logger service. Wrapper for console log, will log only on development environment (production === false)
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