-
-
Notifications
You must be signed in to change notification settings - Fork 503
Expand file tree
/
Copy pathLogger.js
More file actions
100 lines (84 loc) · 2.08 KB
/
Logger.js
File metadata and controls
100 lines (84 loc) · 2.08 KB
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
92
93
94
95
96
97
98
99
100
/** @typedef {import("./BundleAnalyzerPlugin").EXPECTED_ANY} EXPECTED_ANY */
/** @typedef {"debug" | "info" | "warn" | "error" | "silent"} Level */
/** @type {Level[]} */
const LEVELS = ["debug", "info", "warn", "error", "silent"];
/** @type {Map<Level, string>} */
const LEVEL_TO_CONSOLE_METHOD = new Map([
["debug", "log"],
["info", "log"],
["warn", "log"],
]);
class Logger {
/** @type {Level[]} */
static levels = LEVELS;
/** @type {Level} */
static defaultLevel = "info";
/**
* @param {Level=} level level
*/
constructor(level = Logger.defaultLevel) {
/** @type {Set<Level>} */
this.activeLevels = new Set();
this.setLogLevel(level);
}
/**
* @param {Level} level level
*/
setLogLevel(level) {
const levelIndex = LEVELS.indexOf(level);
if (levelIndex === -1) {
throw new Error(
`Invalid log level "${level}". Use one of these: ${LEVELS.join(", ")}`,
);
}
this.activeLevels.clear();
for (const [i, level] of LEVELS.entries()) {
if (i >= levelIndex) this.activeLevels.add(level);
}
}
/**
* @template {EXPECTED_ANY[]} T
* @param {T} args args
*/
debug(...args) {
if (!this.activeLevels.has("debug")) return;
this._log("debug", ...args);
}
/**
* @template {EXPECTED_ANY[]} T
* @param {T} args args
*/
info(...args) {
if (!this.activeLevels.has("info")) return;
this._log("info", ...args);
}
/**
* @template {EXPECTED_ANY[]} T
* @param {T} args args
*/
error(...args) {
if (!this.activeLevels.has("error")) return;
this._log("error", ...args);
}
/**
* @template {EXPECTED_ANY[]} T
* @param {T} args args
*/
warn(...args) {
if (!this.activeLevels.has("warn")) return;
this._log("warn", ...args);
}
/**
* @template {EXPECTED_ANY[]} T
* @param {Level} level level
* @param {T} args args
*/
_log(level, ...args) {
// eslint-disable-next-line no-console
console[
/** @type {Exclude<Level, "silent">} */
(LEVEL_TO_CONSOLE_METHOD.get(level) || level)
](...args);
}
}
module.exports = Logger;