import type { ILogger, LogLevel, LoggerOptions } from './types.js'; import { getLogLevel, getThrowError, shouldLog } from './utils.js'; export class Logger implements ILogger { private packageName: string; private envPrefix?: string; private debugNamespace?: string; private threshold!: LogLevel; private mustThrow!: boolean; constructor(options: LoggerOptions) { this.packageName = options.packageName; this.envPrefix = options.envPrefix; this.debugNamespace = options.debugNamespace; this.threshold = getLogLevel(this.envPrefix); this.mustThrow = getThrowError(this.envPrefix); } private log(level: LogLevel, message: string, data?: any): void { const shouldOutput = shouldLog(level, this.threshold, this.debugNamespace); if (shouldOutput) { const timestamp = new Date().toISOString(); const prefix = `[${timestamp}] [${this.packageName}]${this.debugNamespace ? ` [${this.debugNamespace}]` : ''} [${level.toUpperCase()}]`; const consoleMethod = level === 'error' ? 'error' : level === 'warn' ? 'warn' : 'log'; if (data) { console[consoleMethod](`${prefix} ${message}`, data); } else { console[consoleMethod](`${prefix} ${message}`); } } if (level === 'error' && this.mustThrow) { if (data instanceof Error) { throw data; } throw new Error(message); } } verbose(message: string, data?: any): void { this.log('verbose', message, data); } debug(message: string, data?: any): void { this.log('debug', message, data); } info(message: string, data?: any): void { this.log('info', message, data); } warn(message: string, data?: any): void { this.log('warn', message, data); } error(message: string, data?: any): void { this.log('error', message, data); } } export * from './types.js';