|
1 | | -import type { LogLevel } from '../types/shared'; |
| 1 | +import type { LogLevelString } from '../types/shared'; |
| 2 | +import { LogLevel } from '../types/shared'; |
2 | 3 |
|
3 | 4 | class Logger { |
4 | | - private readonly logLevelMap: Record<LogLevel, number> = { |
5 | | - debug: 1, |
6 | | - info: 2, |
7 | | - warn: 3, |
8 | | - error: 4, |
9 | | - none: 5, |
10 | | - }; |
| 5 | + private currentLogLevel = LogLevel.debug; |
11 | 6 |
|
12 | | - private currentLogLevel: LogLevel = 'debug'; |
13 | | - private currentLogLevelIndex: number = this.logLevelMap[this.currentLogLevel]; |
14 | | - |
15 | | - setLogLevel(level: LogLevel) { |
16 | | - if (this.currentLogLevel === level) return; // no change |
17 | | - |
18 | | - if (this.logLevelMap[level] === undefined) { |
| 7 | + setLogLevel(level: LogLevelString) { |
| 8 | + if (LogLevel[level] === undefined) { |
19 | 9 | console.error(`Invalid log level: ${level}`); |
20 | 10 | return; |
21 | 11 | } |
22 | 12 |
|
23 | | - this.currentLogLevel = level; |
24 | | - this.currentLogLevelIndex = this.logLevelMap[level]; |
| 13 | + if (LogLevel[level] === this.currentLogLevel) return; // no change |
| 14 | + |
| 15 | + this.currentLogLevel = LogLevel[level]; |
25 | 16 | } |
26 | 17 |
|
27 | 18 | private log(level: LogLevel, ...args: any[]) { |
28 | | - if (this.currentLogLevel === 'none') return; |
29 | | - if (this.logLevelMap[level] < this.currentLogLevelIndex) return; |
| 19 | + if (this.currentLogLevel === LogLevel.none) return; |
| 20 | + if (level < this.currentLogLevel) return; |
30 | 21 |
|
31 | 22 | switch (level) { |
32 | | - case 'debug': |
| 23 | + case LogLevel.debug: |
33 | 24 | console.debug(...args); |
34 | 25 | break; |
35 | | - case 'info': |
| 26 | + case LogLevel.info: |
36 | 27 | console.log(...args); |
37 | 28 | break; |
38 | | - case 'warn': |
| 29 | + case LogLevel.warn: |
39 | 30 | console.warn(...args); |
40 | 31 | break; |
41 | | - case 'error': |
| 32 | + case LogLevel.error: |
42 | 33 | console.error(...args); |
43 | 34 | break; |
44 | 35 | } |
45 | 36 | } |
46 | 37 |
|
47 | 38 | debug(...args: any[]) { |
48 | | - this.log('debug', ...args); |
| 39 | + this.log(LogLevel.debug, ...args); |
49 | 40 | } |
50 | 41 | info(...args: any[]) { |
51 | | - this.log('info', ...args); |
| 42 | + this.log(LogLevel.info, ...args); |
52 | 43 | } |
53 | 44 | warn(...args: any[]) { |
54 | | - this.log('warn', ...args); |
| 45 | + this.log(LogLevel.warn, ...args); |
55 | 46 | } |
56 | 47 | error(...args: any[]) { |
57 | | - this.log('error', ...args); |
| 48 | + this.log(LogLevel.error, ...args); |
58 | 49 | } |
59 | 50 | } |
60 | 51 |
|
|
0 commit comments