/
logger.ts
93 lines (84 loc) · 2.18 KB
/
logger.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
92
93
/* eslint no-console: 0 */
import chalk from 'chalk'
import readline from 'readline'
export type LogType = 'error' | 'warn' | 'info'
export type LogLevel = LogType | 'silent'
export interface Logger {
info(msg: string, options?: LogOptions): void
warn(msg: string, options?: LogOptions): void
error(msg: string, options?: LogOptions): void
clearScreen(type: LogType): void
}
export interface LogOptions {
clear?: boolean
timestamp?: boolean
}
const LogLevels: Record<LogLevel, number> = {
silent: 0,
error: 1,
warn: 2,
info: 3
}
let lastType: LogType | undefined
let lastMsg: string | undefined
let sameCount = 0
function clearScreen() {
const blank = '\n'.repeat(process.stdout.rows - 2)
console.log(blank)
readline.cursorTo(process.stdout, 0, 0)
readline.clearScreenDown(process.stdout)
}
export function createLogger(
level: LogLevel = 'info',
allowClearScreen = true
): Logger {
const thresh = LogLevels[level]
const clear = allowClearScreen ? clearScreen : () => {}
function output(type: LogType, msg: string, options: LogOptions = {}) {
if (thresh >= LogLevels[type]) {
const method = type === 'info' ? 'log' : type
const format = () => {
if (options.timestamp) {
const tag =
type === 'info'
? chalk.cyan.bold(`[vite]`)
: type === 'warn'
? chalk.yellow.bold(`[vite]`)
: chalk.red.bold(`[vite]`)
return `${chalk.dim(new Date().toLocaleTimeString())} ${tag} ${msg}`
} else {
return msg
}
}
if (type === lastType && msg === lastMsg) {
sameCount++
clear()
console[method](format(), chalk.yellow(`(x${sameCount + 1})`))
} else {
sameCount = 0
lastMsg = msg
lastType = type
if (options.clear) {
clear()
}
console[method](format())
}
}
}
return {
info(msg, opts) {
output('info', msg, opts)
},
warn(msg, opts) {
output('warn', msg, opts)
},
error(msg, opts) {
output('error', msg, opts)
},
clearScreen(type) {
if (thresh >= LogLevels[type]) {
clear()
}
}
}
}