neko/src/component/utils/logger.ts

60 lines
1.8 KiB
TypeScript
Raw Normal View History

2020-11-06 05:15:21 +13:00
export class Logger {
2021-10-04 11:22:11 +13:00
// eslint-disable-next-line
constructor(
protected readonly _scope: string = 'main',
) {}
2020-11-06 05:15:21 +13:00
2021-09-10 09:23:34 +12:00
protected _console(level: string, m: string, fields?: Record<string, any>) {
let t = ''
const args = []
for (const name in fields) {
2021-09-13 03:00:11 +12:00
if (fields[name] instanceof Error) {
t += ' %c%s="%s"%c'
args.push('color:#d84949;', name, (fields[name] as Error).message, '')
continue
}
2021-09-10 09:40:33 +12:00
if (typeof fields[name] === 'string' || fields[name] instanceof String) {
t += ' %c%s=%c"%s"'
} else {
t += ' %c%s=%c%o'
}
2021-09-10 09:23:34 +12:00
args.push('color:#498ad8;', name, '', fields[name])
}
const scope = this._scope
switch (level) {
case 'error':
console.error('[%cNEKO%c] [%s] %cERR%c %s' + t, 'color:#498ad8;', '', scope, 'color:#d84949;', '', m, ...args)
break
case 'warn':
console.warn('[%cNEKO%c] [%s] %cWRN%c %s' + t, 'color:#498ad8;', '', scope, 'color:#eae364;', '', m, ...args)
break
case 'info':
console.info('[%cNEKO%c] [%s] %cINF%c %s' + t, 'color:#498ad8;', '', scope, 'color:#4ac94c;', '', m, ...args)
break
default:
case 'debug':
console.debug('[%cNEKO%c] [%s] %cDBG%c %s' + t, 'color:#498ad8;', '', scope, 'color:#eae364;', '', m, ...args)
break
}
}
public error(message: string, fields?: Record<string, any>) {
this._console('error', message, fields)
2020-11-06 05:15:21 +13:00
}
2021-09-10 09:23:34 +12:00
public warn(message: string, fields?: Record<string, any>) {
this._console('warn', message, fields)
2020-11-06 05:15:21 +13:00
}
2021-09-10 09:23:34 +12:00
public info(message: string, fields?: Record<string, any>) {
this._console('info', message, fields)
2020-11-06 05:15:21 +13:00
}
2021-09-10 09:23:34 +12:00
public debug(message: string, fields?: Record<string, any>) {
this._console('debug', message, fields)
2020-11-06 05:15:21 +13:00
}
}