Skip to content

Commit 52d67ab

Browse files
committed
feat: add logger
1 parent d46766f commit 52d67ab

2 files changed

Lines changed: 100 additions & 0 deletions

File tree

__test__/lib/logger.test.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import Logger from '../../lib/log/index'
2+
3+
describe('logger', () => {
4+
it('logger test', () => {
5+
const logger = new Logger()
6+
7+
logger.info('log')
8+
expect(true).toBe(true)
9+
})
10+
})

lib/log/index.ts

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
const LOG_LEVELS = {
2+
ERROR: 0,
3+
WARNING: 1,
4+
NORMAL: 2,
5+
DEBUG: 3,
6+
TRACE: 4,
7+
}
8+
9+
const ANSI_COLORS = {
10+
[LOG_LEVELS.ERROR]: '\x1b[31m', // 红色
11+
[LOG_LEVELS.WARNING]: '\x1b[33m', // 黄色
12+
[LOG_LEVELS.NORMAL]: '\x1b[32m', // 绿色
13+
[LOG_LEVELS.DEBUG]: '\x1b[34m', // 蓝色
14+
[LOG_LEVELS.TRACE]: '\x1b[35m' // 紫色
15+
}
16+
17+
const LOG_LEVEL_NAMES = {
18+
[LOG_LEVELS.ERROR]: 'error',
19+
[LOG_LEVELS.WARNING]: 'warning',
20+
[LOG_LEVELS.NORMAL]: 'info',
21+
[LOG_LEVELS.DEBUG]: 'debug',
22+
[LOG_LEVELS.TRACE]: 'trace'
23+
}
24+
25+
function isUnicodeSupported() {
26+
// @ts-ignore
27+
return typeof window === 'undefined'
28+
}
29+
30+
const unicode = isUnicodeSupported()
31+
const s = (c: string, fallback: string) => (unicode ? c : fallback)
32+
33+
const TYPE_ICONS = {
34+
error: s('✖', '×'),
35+
fatal: s('✖', '×'),
36+
ready: s('✔', '√'),
37+
warn: s('⚠', '‼'),
38+
info: s('ℹ', 'i'),
39+
success: s('✔', '√'),
40+
debug: s('⚙', 'D'),
41+
trace: s('→', '→'),
42+
fail: s('✖', '×'),
43+
start: s('◐', 'o'),
44+
log: ''
45+
}
46+
class Logger {
47+
private level: number
48+
constructor(level = LOG_LEVELS.NORMAL) {
49+
this.level = level
50+
}
51+
52+
setLevel(level: number) {
53+
this.level = level
54+
}
55+
56+
log(level: number, message: string) {
57+
if (level > this.level) {
58+
return
59+
}
60+
const color = ANSI_COLORS[level] || ANSI_COLORS[LOG_LEVELS.NORMAL]
61+
const levelName: string = LOG_LEVEL_NAMES[level]
62+
const icon = Reflect.get(TYPE_ICONS, levelName) || ''
63+
const timestamp = new Date().toLocaleString()
64+
console.log(
65+
`${color}${icon}\x1b[0m [${levelName}] (${timestamp}) ${message}`
66+
)
67+
}
68+
69+
error(message: string) {
70+
this.log(LOG_LEVELS.ERROR, message)
71+
}
72+
73+
warning(message: string) {
74+
this.log(LOG_LEVELS.WARNING, message)
75+
}
76+
77+
normal(message: string) {
78+
this.log(LOG_LEVELS.NORMAL, message)
79+
}
80+
81+
info(message: string) {
82+
this.log(LOG_LEVELS.DEBUG, message)
83+
}
84+
85+
trace(message: string) {
86+
this.log(LOG_LEVELS.TRACE, message)
87+
}
88+
}
89+
90+
export default Logger

0 commit comments

Comments
 (0)