type LoggerConfigType = {
namespace?: string
}
type InterceptorFuncType = (config: LoggerConfigType) => void
const enum LogLevel {
Log,
Warning,
Error,
}
const __DEV__ = import.meta.env.MODE
const Styles = ['color: green;', 'color: orange;', 'color: red;']
const Methods = ['info', 'warn', 'error'] as const
class Logger {
private beforeFuns: Array<InterceptorFuncType> = []
private afterFuns: Array<InterceptorFuncType> = []
private config: LoggerConfigType = {}
constructor(namespace = 'unknown') {
this.config.namespace = `[${namespace}]`
}
public create(namespace = 'unknown') {
return new Logger(namespace);
}
private _log(level: LogLevel, args: unknown[]) {
if (__DEV__ !== 'development') return
this.beforeFuns.forEach(func => func(this.config))
console[Methods[level]](`%c${this.config.namespace}`, Styles[level], ...args)
}
private addInterceptor(func: InterceptorFuncType, isBefore = true) {
if(typeof func !== 'function'){
return this.error('拦截器函数不符合规范')
}
if(isBefore){
this.beforeFuns.push(func)
}
this.afterFuns.push(func)
return this
}
public addBeforeFunc(func: InterceptorFuncType) {
this.addInterceptor(func)
return this
}
public addAfterFunc(func: InterceptorFuncType) {
this.addInterceptor(func, false)
return this
}
public info(...args: unknown[]) {
this._log(LogLevel.Log, args)
return this
}
public warn(...args: unknown[]) {
this._log(LogLevel.Warning, args)
return this
}
public error(...args: unknown[]) {
this._log(LogLevel.Error, args)
return this
}
public setNamespace(namespace = '') {
this.config.namespace = `[${namespace}]`
return this
}
public reportLog() {
this.info()
}
public reportEvent() {
this.info()
}
public reportException() {
this.error()
}
}
export default new Logger()