File size: 1,549 Bytes
c13f797
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import { config } from '../config';

type LogLevel = 'debug' | 'info' | 'warn' | 'error';

const levels: Record<LogLevel, number> = {
  debug: 0,
  info: 1,
  warn: 2,
  error: 3,
};

const colors: Record<LogLevel, string> = {
  debug: '\x1b[36m', // cyan
  info: '\x1b[32m',  // green
  warn: '\x1b[33m',  // yellow
  error: '\x1b[31m', // red
};

const reset = '\x1b[0m';
const bold = '\x1b[1m';

class Logger {
  private minLevel: number;

  constructor() {
    this.minLevel = levels[config.logLevel] ?? levels.info;
  }

  private log(level: LogLevel, module: string, message: string, data?: unknown): void {
    if (levels[level] < this.minLevel) return;

    const timestamp = new Date().toISOString();
    const color = colors[level];
    const levelStr = level.toUpperCase().padEnd(5);
    const moduleStr = `[${module}]`.padEnd(20);

    const line = `${color}${bold}${levelStr}${reset} ${timestamp} ${moduleStr} ${message}`;
    console.log(line);

    if (data !== undefined) {
      console.log(JSON.stringify(data, null, 2));
    }
  }

  debug(module: string, message: string, data?: unknown): void {
    this.log('debug', module, message, data);
  }

  info(module: string, message: string, data?: unknown): void {
    this.log('info', module, message, data);
  }

  warn(module: string, message: string, data?: unknown): void {
    this.log('warn', module, message, data);
  }

  error(module: string, message: string, data?: unknown): void {
    this.log('error', module, message, data);
  }
}

export const logger = new Logger();