-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
75 lines (67 loc) · 2.28 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
75
export enum LogLevel {
TRACE = 'trace',
DEBUG = 'debug',
INFO = 'info',
WARN = 'warn',
ERROR = 'error',
}
export interface LoggingMethods {
trace(...args: any[]): void;
debug(...args: any[]): void;
log(...args: any[]): void;
info(...args: any[]): void;
warn(...args: any[]): void;
error(...args: any[]): void;
}
export interface Logger extends LoggingMethods {
setLevel(level: LogLevel): void;
getLevel(): LogLevel;
setFormatter(formatter: Formatter): void;
setReporter(reporter: Reporter): void;
}
export interface Formatter {
(args: any[], methodName: keyof LoggingMethods, logLevel: LogLevel): any[];
}
export interface Reporter {
(args: any[], methodName: keyof LoggingMethods, logLevel: LogLevel): void;
}
export const defaultFormatter: Formatter = (args) => args;
export const defaultReporter: Reporter = (args, methodName) =>
typeof console !== 'undefined' && console[methodName] && console[methodName](...args);
export default (): Logger => {
const levelOrder = [LogLevel.TRACE, LogLevel.DEBUG, LogLevel.INFO, LogLevel.WARN, LogLevel.ERROR];
let currentLevelIndex = levelOrder.indexOf(LogLevel.WARN);
let report = defaultReporter;
let format = defaultFormatter;
const createMethod = (methodName: keyof LoggingMethods, logLevel: LogLevel) => {
const levelIndex = levelOrder.indexOf(logLevel);
return (...args: any[]) => {
if (currentLevelIndex > levelIndex) return;
report(format(args, methodName, logLevel), methodName, logLevel);
};
};
return {
trace: createMethod('trace', LogLevel.TRACE),
debug: createMethod('debug', LogLevel.DEBUG),
log: createMethod('log', LogLevel.INFO),
info: createMethod('info', LogLevel.INFO),
warn: createMethod('warn', LogLevel.WARN),
error: createMethod('error', LogLevel.ERROR),
setLevel(logLevel: LogLevel) {
const idx = levelOrder.indexOf(logLevel);
if (idx === -1) throw new Error(`Unknown log level ${logLevel}`);
currentLevelIndex = idx;
},
getLevel() {
const level = levelOrder[currentLevelIndex];
if (!level) throw new Error(`Invalid level set (${level})`);
return level;
},
setReporter(reporter: Reporter) {
report = reporter;
},
setFormatter(formatter: Formatter) {
format = formatter;
},
};
};