summaryrefslogtreecommitdiff
path: root/std/log/logger.ts
blob: 99d17ef48f018b3da6f34fcfbf2ba8bc56a0d908 (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
52
53
54
55
56
57
58
59
60
61
62
63
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { LogLevel, getLevelByName, getLevelName } from "./levels.ts";
import { BaseHandler } from "./handlers.ts";

export interface LogRecord {
  msg: string;
  args: unknown[];
  datetime: Date;
  level: number;
  levelName: string;
}

export class Logger {
  level: number;
  levelName: string;
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  handlers: any[];

  constructor(levelName: string, handlers?: BaseHandler[]) {
    this.level = getLevelByName(levelName);
    this.levelName = levelName;

    this.handlers = handlers || [];
  }

  _log(level: number, msg: string, ...args: unknown[]): void {
    if (this.level > level) return;

    // TODO: it'd be a good idea to make it immutable, so
    // no handler mangles it by mistake
    // TODO: iterpolate msg with values
    const record: LogRecord = {
      msg: msg,
      args: args,
      datetime: new Date(),
      level: level,
      levelName: getLevelName(level)
    };
    this.handlers.forEach((handler): void => {
      handler.handle(record);
    });
  }

  debug(msg: string, ...args: unknown[]): void {
    this._log(LogLevel.DEBUG, msg, ...args);
  }

  info(msg: string, ...args: unknown[]): void {
    this._log(LogLevel.INFO, msg, ...args);
  }

  warning(msg: string, ...args: unknown[]): void {
    this._log(LogLevel.WARNING, msg, ...args);
  }

  error(msg: string, ...args: unknown[]): void {
    this._log(LogLevel.ERROR, msg, ...args);
  }

  critical(msg: string, ...args: unknown[]): void {
    this._log(LogLevel.CRITICAL, msg, ...args);
  }
}