UNPKG

938 BJavaScriptView Raw
1const LEVELS = [
2 'info',
3 'warn',
4 'error',
5 'silent'
6];
7
8const LEVEL_TO_CONSOLE_METHOD = new Map([
9 ['info', 'log'],
10 ['warn', 'log']
11]);
12
13class Logger {
14
15 static levels = LEVELS;
16
17 constructor(level = 'info') {
18 this.activeLevels = new Set();
19 this.setLogLevel(level);
20 }
21
22 setLogLevel(level) {
23 const levelIndex = LEVELS.indexOf(level);
24
25 if (levelIndex === -1) throw new Error(`Invalid log level "${level}". Use one of these: ${LEVELS.join(', ')}`);
26
27 this.activeLevels.clear();
28
29 for (const [i, level] of LEVELS.entries()) {
30 if (i >= levelIndex) this.activeLevels.add(level);
31 }
32 }
33
34 _log(level, ...args) {
35 console[LEVEL_TO_CONSOLE_METHOD.get(level) || level](...args);
36 }
37
38};
39
40LEVELS.forEach(level => {
41 if (level === 'silent') return;
42
43 Logger.prototype[level] = function (...args) {
44 if (this.activeLevels.has(level)) this._log(level, ...args);
45 };
46});
47
48module.exports = Logger;