/
log.ts
84 lines (70 loc) · 1.83 KB
/
log.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
import * as colors from 'colorette'
type LOG_TYPE = 'info' | 'success' | 'error' | 'warn'
export const colorize = (type: LOG_TYPE, data: any, onlyImportant = false) => {
if (onlyImportant && (type === 'info' || type === 'success')) return data
const color =
type === 'info'
? 'blue'
: type === 'error'
? 'red'
: type === 'warn'
? 'yellow'
: 'green'
return colors[color](data)
}
export const makeLabel = (
name: string | undefined,
input: string,
type: LOG_TYPE
) => {
return [
name && `${colors.dim('[')}${name.toUpperCase()}${colors.dim(']')}`,
colorize(type, input.toUpperCase()),
]
.filter(Boolean)
.join(' ')
}
let silent = false
export function setSilent(isSilent?: boolean) {
silent = !!isSilent
}
export type Logger = ReturnType<typeof createLogger>
export const createLogger = (name?: string) => {
return {
setName(_name: string) {
name = _name
},
success(label: string, ...args: any[]) {
return this.log(label, 'success', ...args)
},
info(label: string, ...args: any[]) {
return this.log(label, 'info', ...args)
},
error(label: string, ...args: any[]) {
return this.log(label, 'error', ...args)
},
warn(label: string, ...args: any[]) {
return this.log(label, 'warn', ...args)
},
log(
label: string,
type: 'info' | 'success' | 'error' | 'warn',
...data: unknown[]
) {
switch (type) {
case 'error': {
return console.error(
makeLabel(name, label, type),
...data.map((item) => colorize(type, item, true))
)
}
default:
if (silent) return
console.log(
makeLabel(name, label, type),
...data.map((item) => colorize(type, item, true))
)
}
},
}
}