import {TypedEmitter, TypedEvents} from './emitter'; import {JSONSanitize} from './objects.ts'; export const CliEffects = { CLEAR: "\x1b[0m", BRIGHT: "\x1b[1m", DIM: "\x1b[2m", UNDERSCORE: "\x1b[4m", BLINK: "\x1b[5m", REVERSE: "\x1b[7m", HIDDEN: "\x1b[8m", } export const CliForeground = { BLACK: '\x1b[30m', RED: '\x1b[31m', GREEN: '\x1b[32m', YELLOW: '\x1b[33m', BLUE: '\x1b[34m', MAGENTA: '\x1b[35m', CYAN: '\x1b[36m', LIGHT_GREY: '\x1b[37m', GREY: '\x1b[90m', LIGHT_RED: '\x1b[91m', LIGHT_GREEN: '\x1b[92m', LIGHT_YELLOW: '\x1b[93m', LIGHT_BLUE: '\x1b[94m', LIGHT_MAGENTA: '\x1b[95m', LIGHT_CYAN: '\x1b[96m', WHITE: '\x1b[97m', } export const CliBackground = { BLACK: "\x1b[40m", RED: "\x1b[41m", GREEN: "\x1b[42m", YELLOW: "\x1b[43m", BLUE: "\x1b[44m", MAGENTA: "\x1b[45m", CYAN: "\x1b[46m", WHITE: "\x1b[47m", GREY: "\x1b[100m", } export enum LOG_LEVEL { ERROR = 0, WARN = 1, INFO = 2, LOG = 3, DEBUG = 4, } export type LoggerEvents = TypedEvents & { 'ERROR': (...args: any[]) => any; 'WARN': (...args: any[]) => any; 'INFO': (...args: any[]) => any; 'LOG': (...args: any[]) => any; 'DEBUG': (...args: any[]) => any; }; export class Logger extends TypedEmitter { static LOG_LEVEL: LOG_LEVEL = LOG_LEVEL.DEBUG; constructor(public readonly namespace?: string) { super(); } protected format(...text: any[]): string { const now = new Date(); const timestamp = `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()} ${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}.${now.getMilliseconds().toString().padEnd(3, '0')}`; return `${timestamp}${this.namespace ? ` [${this.namespace}]` : ''} ${text.map(t => typeof t == 'string' ? t : JSONSanitize(t, 2)).join(' ')}`; } debug(...args: any[]) { if(Logger.LOG_LEVEL < LOG_LEVEL.DEBUG) return; const str = this.format(...args); Logger.emit(LOG_LEVEL.DEBUG, str); console.debug(CliForeground.LIGHT_GREY + str + CliEffects.CLEAR); } log(...args: any[]) { if(Logger.LOG_LEVEL < LOG_LEVEL.LOG) return; const str = this.format(...args); Logger.emit(LOG_LEVEL.LOG, str); console.log(CliEffects.CLEAR + str); } info(...args: any[]) { if(Logger.LOG_LEVEL < LOG_LEVEL.INFO) return; const str = this.format(...args); Logger.emit(LOG_LEVEL.INFO, str); console.info(CliForeground.BLUE + str + CliEffects.CLEAR); } warn(...args: any[]) { if(Logger.LOG_LEVEL < LOG_LEVEL.WARN) return; const str = this.format(...args); Logger.emit(LOG_LEVEL.WARN, str); console.warn(CliForeground.YELLOW + str + CliEffects.CLEAR); } error(...args: any[]) { if(Logger.LOG_LEVEL < LOG_LEVEL.ERROR) return; const str = this.format(...args); Logger.emit(LOG_LEVEL.ERROR, str); console.error(CliForeground.RED + str + CliEffects.CLEAR); } }