-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathlog.ts
91 lines (78 loc) · 1.9 KB
/
log.ts
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import { colors } from "./deps.ts";
import { Level, LevelName } from "./interface.ts";
export class Timing {
#t = performance.now();
reset() {
this.#t = performance.now();
}
stop(message: string) {
const now = performance.now();
const d = Math.round(now - this.#t);
let cf = colors.green;
if (d > 10000) {
cf = colors.red;
} else if (d > 1000) {
cf = colors.yellow;
}
console.debug(colors.dim("TIMING"), message, "in", cf(d + "ms"));
this.#t = now;
}
}
export class Logger {
#level: Level = Level.Info;
get level(): Level {
return this.#level;
}
setLevel(level: LevelName): void {
switch (level) {
case "debug":
this.#level = Level.Debug;
break;
case "info":
this.#level = Level.Info;
break;
case "warn":
this.#level = Level.Warn;
break;
case "error":
this.#level = Level.Error;
break;
case "fatal":
this.#level = Level.Fatal;
break;
}
}
debug(...args: unknown[]): void {
if (this.#level <= Level.Debug) {
console.debug(colors.dim("DEBUG"), ...args);
}
}
info(...args: unknown[]): void {
if (this.#level <= Level.Info) {
console.log(colors.green("INFO"), ...args);
}
}
warn(...args: unknown[]): void {
if (this.#level <= Level.Warn) {
console.warn(colors.yellow("WARN"), ...args);
}
}
error(...args: unknown[]): void {
if (this.#level <= Level.Error) {
console.error(colors.red("ERROR"), ...args);
}
}
fatal(...args: unknown[]): void {
if (this.#level <= Level.Fatal) {
console.error(colors.red("FATAL"), ...args);
Deno.exit(1);
}
}
timing(): { reset(): void; stop(message: string): void } {
if (this.level === Level.Debug) {
return new Timing();
}
return { reset: () => {}, stop: () => {} };
}
}
export default new Logger();