Last active
May 22, 2019 18:36
-
-
Save AhsanAyaz/49b1c62d52b296dc5aeef09efb9d60a5 to your computer and use it in GitHub Desktop.
Custom logging service for Angular
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 { Injectable } from '@angular/core'; | |
import { BehaviorSubject, Observable } from 'rxjs'; | |
export interface LoggerConfig { | |
prefix?: string; | |
color?: string; | |
enabled: boolean; | |
} | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class LoggerProvider { | |
defaultConfig: LoggerConfig = {prefix: '', color: '#76BE43', enabled: true}; | |
loggedSubj = new BehaviorSubject<any>(null); | |
logged$: Observable<any>; | |
method: string; | |
levelMap = { | |
warn: 'warn', | |
error: 'error', | |
log: 'log', | |
info: 'info' | |
}; | |
constructor(private config?: LoggerConfig) { | |
this.config = this.config ? {...this.defaultConfig, ...this.config} : this.defaultConfig; | |
this.logged$ = this.loggedSubj.asObservable(); | |
} | |
log(...params) { | |
this.method = this.levelMap.log; | |
this.writeToLog.apply(this, arguments); | |
} | |
error(...params) { | |
this.method = this.levelMap.error; | |
this.writeToLog.apply(this, arguments); | |
} | |
info(...params) { | |
this.method = this.levelMap.info; | |
this.writeToLog.apply(this, arguments); | |
} | |
warn(...params) { | |
this.method = this.levelMap.warn; | |
this.writeToLog.apply(this, arguments); | |
} | |
writeToLog() { | |
const args = []; | |
for (let i = 0; i < arguments.length; ++i) { | |
args.push(arguments[i]); | |
} | |
let message = args.map((arg) => { | |
if (typeof arg === 'object') { | |
return JSON.stringify(arg); | |
} | |
return arg; | |
}).join(', '); | |
const logMsg = `${this.config.prefix ? this.config.prefix + ' - ' : ''}${this.method}${message}`; | |
console[this.method](`%c${logMsg}`, `color: ${this.config.color}; font-weight: bold;`); | |
this.loggedSubj.next({ | |
prefix: this.config.prefix, | |
method: this.method, | |
message | |
}); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment