summaryrefslogtreecommitdiff
path: root/std/log/logger.ts
blob: 6a12325e8684a75180caf11bbf2bfb2d9a7d0d8d (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
64
65
66
67
68
69
70
71
72
73
74
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import {
  LogLevels,
  getLevelByName,
  getLevelName,
  LevelName,
} from "./levels.ts";
import { BaseHandler } from "./handlers.ts";

export class LogRecord {
  readonly msg: string;
  #args: unknown[];
  #datetime: Date;
  readonly level: number;
  readonly levelName: string;

  constructor(msg: string, args: unknown[], level: number) {
    this.msg = msg;
    this.#args = [...args];
    this.level = level;
    this.#datetime = new Date();
    this.levelName = getLevelName(level);
  }
  get args(): unknown[] {
    return [...this.#args];
  }
  get datetime(): Date {
    return new Date(this.#datetime.getTime());
  }
}

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

  constructor(levelName: LevelName, 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;

    const record: LogRecord = new LogRecord(msg, args, level);

    this.handlers.forEach((handler): void => {
      handler.handle(record);
    });
  }

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

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

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

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

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