/
index.ts
74 lines (60 loc) · 1.65 KB
/
index.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
import genericDebug from 'debug';
import type { Debugger } from 'debug';
import pc from 'picocolors';
type LogLevel = 'error' | 'warn' | 'info' | 'debug';
const levels = ['error', 'warn', 'info', 'debug'];
const currentLevel = levels.indexOf(process.env.LINARIA_LOG || 'warn');
const linariaLogger = genericDebug('linaria');
const loggers = new Map<string, Debugger>();
function gerOrCreate(namespace: string | null | undefined): Debugger {
if (!namespace) return linariaLogger;
const lastIndexOf = namespace.lastIndexOf(':');
if (!loggers.has(namespace)) {
loggers.set(
namespace,
gerOrCreate(namespace.substr(0, lastIndexOf)).extend(
namespace.substr(lastIndexOf + 1)
)
);
}
return loggers.get(namespace)!;
}
const format = <T>(text: T) => {
if (typeof text === 'string') {
return text.replace(/\n/g, '\n\t');
}
return text;
};
function log(
level: LogLevel,
namespaces: string,
arg1: any | (() => void),
...restArgs: any[]
) {
if (currentLevel < levels.indexOf(level)) {
return;
}
const logger = gerOrCreate(namespaces);
if (!logger.enabled) return;
if (typeof arg1 === 'function') {
const text = arg1();
if (text) {
logger('', format(text), ...restArgs);
}
return;
}
logger('', format(arg1), ...restArgs);
}
export const debug = log.bind(null, 'debug');
export const info = log.bind(null, 'info');
export const warn = log.bind(null, 'warn');
export const error = log.bind(null, 'error');
export const notify = (message: string) => {
console.log(
pc.red(
message.replace(/(`.*?`)/g, (s) =>
pc.italic(s.substring(1, s.length - 1))
)
)
);
};