summaryrefslogtreecommitdiff
path: root/src/utils/logger.ts
blob: 80126c37776c53e383823ad3cee39dc7506c28be (plain)
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
export interface TracingLogger {
  info(log: string): void;
  warn(log: string): void;
  error(log: string): void;
  debug(log: string): void;

  createChild(prefix: string): TracingLogger;
}

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

export class ConsoleTracingLogger implements TracingLogger {
  protected prefix: string;
  private levels: LogLevel[];

  constructor(prefix: string, levels: LogLevel[] = ['warn', 'error']) {
    this.prefix = prefix;
    this.levels = levels;
  }

  private makePrefix(level: LogLevel): string {
    return `[${new Date().toISOString()}] ${level} (${this.prefix}) > `;
  }

  public info(log: string) {
    if (this.levels.includes('info'))
      console.log(this.makePrefix('info') + log);
  }

  public warn(log: string) {
    if (this.levels.includes('warn'))
      console.warn(this.makePrefix('warn') + log);
  }

  public error(log: string) {
    if (this.levels.includes('error'))
      console.error(this.makePrefix('error') + log);
  }

  public debug(log: string) {
    if (this.levels.includes('debug'))
      console.debug(this.makePrefix('debug') + log);
  }

  public createChild(prefix: string, levels?: LogLevel[]) {
    return new ConsoleTracingLogger(
      `${this.prefix} -> ${prefix}`,
      levels ?? this.levels,
    );
  }
}