-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
135 lines (127 loc) · 2.81 KB
/
middleware.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
/**
* @module logger/middleware
* Description: Default middleware for logging API
*/
import {
AnyObject,
} from '../types';
import {
colorEscapeCodes,
isNode,
} from '../utils';
/**
* Name: consoleLog
* Description: Middleware for outputting logs via stdout/console
* @param api
* @returns Middleware for console logging
*/
export const consoleLog = (api: AnyObject) => {
return (middleware: any) => {
return (params: AnyObject) => {
if (api.action.type === 'LOGGER_LOG_LINE') {
const {
logLine,
output,
} = params;
const {
lineOptions,
logRecord,
} = logLine;
const { level } = lineOptions;
// NOTE: LogLevel 'fatal' will use console.error in this case
output[level === 'fatal' ? 'error' : level](logRecord.formatted);
}
return middleware(params);
};
}
};
/**
* Name: createJsonLine
* Description: Middleware for creating a log record
* @param api
* @returns Middleware for creatibg log records
*/
export const createJsonLine = (api: AnyObject) => {
return (middleware: any) => {
return (params: AnyObject) => {
const {
args,
lineOptions,
} = params;
if (api.action.type === 'LOGGER_CREATE_LINE') {
return middleware({
lineOptions,
logRecord: {
raw: {
args,
lineOptions,
},
formatted: lineOptions.formatter({ args, lineOptions }),
},
});
}
return middleware(params);
};
}
};
/**
* Name: createLineFormatter
* Description: Default log line string formatter
* @template F - F: log line format
* @param params args (what to log), lineOptions, amd template (formatter function)
* @returns string
*/
export const createLineFormatter = <
F = string
>(params: AnyObject): F => {
const {
args,
lineOptions,
template = defaultLineTemplate,
} = params;
const {
level,
prefix,
timeStamp,
} = lineOptions;
const escapeStart: string = isNode() ? colorEscapeCodes[level] : '';
const escapeStop: string = isNode() ? colorEscapeCodes.stop : '';
return template({
args,
escapeStart,
escapeStop,
level,
prefix,
timeStamp,
});
};
/**
* Name: defaultLineTemplate
* Description: Default log line string formatter
* @param params
* @returns string
*/
export const defaultLineTemplate = (
params : AnyObject = {}
): string => {
const {
args,
escapeStart,
escapeStop,
level,
prefix,
timeStamp,
} = params;
const bracketInfo = [
timeStamp.formatted,
level.toUpperCase(),
prefix,
]
.filter(Boolean)
.join(' | ');
return [
`${escapeStart}[${bracketInfo}]:`,
JSON.stringify(args, null, 2),
escapeStop,
].join(' ');
};