|
| 1 | +/* eslint-disable @typescript-eslint/no-explicit-any */ |
| 2 | +export type LogLevel = 'DEBUG' | 'INFO' | 'WARN' | 'ERROR' | 'NONE'; |
| 3 | + |
| 4 | +const LEVELS: LogLevel[] = ['DEBUG', 'INFO', 'WARN', 'ERROR', 'NONE']; |
| 5 | + |
| 6 | +export default class Logger { |
| 7 | + private static instance: Logger; |
| 8 | + private logLevel: LogLevel; |
| 9 | + |
| 10 | + private constructor() { |
| 11 | + const storedLogLevel = sessionStorage.getItem('logLevel'); |
| 12 | + |
| 13 | + if (storedLogLevel && this.isValidLogLevel(storedLogLevel as LogLevel)) { |
| 14 | + this.logLevel = storedLogLevel as LogLevel; |
| 15 | + } else { |
| 16 | + this.logLevel = 'INFO'; // Default log level |
| 17 | + sessionStorage.setItem('logLevel', this.logLevel); |
| 18 | + } |
| 19 | + } |
| 20 | + |
| 21 | + public static getInstance(): Logger { |
| 22 | + if (!Logger.instance) { |
| 23 | + Logger.instance = new Logger(); |
| 24 | + } |
| 25 | + |
| 26 | + return Logger.instance; |
| 27 | + } |
| 28 | + |
| 29 | + public getAllLevels(): LogLevel[] { |
| 30 | + return LEVELS; |
| 31 | + } |
| 32 | + |
| 33 | + public getLevel(): LogLevel { |
| 34 | + return this.logLevel; |
| 35 | + } |
| 36 | + |
| 37 | + private isValidLogLevel(logLevel: LogLevel): boolean { |
| 38 | + return LEVELS.includes(logLevel); |
| 39 | + } |
| 40 | + |
| 41 | + private shouldLog(level: LogLevel): boolean { |
| 42 | + return LEVELS.indexOf(level) >= LEVELS.indexOf(this.logLevel); |
| 43 | + } |
| 44 | + |
| 45 | + public debug(message: string, ...args: any[]): void { |
| 46 | + if (this.shouldLog('DEBUG')) { |
| 47 | + console.debug(`[DEBUG]: ${message}`, ...args); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + public info(message: string, ...args: any[]): void { |
| 52 | + if (this.shouldLog('INFO')) { |
| 53 | + console.info(`[INFO]: ${message}`, ...args); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + public warn(message: string, ...args: any[]): void { |
| 58 | + if (this.shouldLog('WARN')) { |
| 59 | + console.warn(`[WARN]: ${message}`, ...args); |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + public error(message: string, ...args: any[]): void { |
| 64 | + if (this.shouldLog('ERROR')) { |
| 65 | + console.error(`[ERROR]: ${message}`, ...args); |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + public setLogLevel(level: LogLevel): void { |
| 70 | + if (this.isValidLogLevel(level)) { |
| 71 | + this.logLevel = level; |
| 72 | + this.info(`Log level set to ${level}`); |
| 73 | + sessionStorage.setItem('logLevel', level); |
| 74 | + } else { |
| 75 | + throw new Error(`Invalid log level: ${level}`); |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + public getLogLevel(): LogLevel { |
| 80 | + return this.logLevel; |
| 81 | + } |
| 82 | +} |
0 commit comments