-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathlogger.ts
More file actions
341 lines (295 loc) · 8.94 KB
/
Copy pathlogger.ts
File metadata and controls
341 lines (295 loc) · 8.94 KB
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
import c from 'chalk';
import iconfirm from '@inquirer/confirm';
import * as symbols from './symbols';
import sanitize from './sanitize';
import getDurationString from './util/duration';
import hrtimestamp from './util/timestamp';
import ensureOptions, { LogOptions, LogLevel } from './options';
// Nice clean log level definitions
// Don't log anything at all (good for unit tests)
// (Note that this doesn't stop a component printing to stdout! It just disables the logger)
export const NONE = 'none';
// Special debug log level - this even hides errors
export const REALLY_NONE = 'none-really';
// Defaults for all the family. Prints what the user absolutely has to know.
// Top-level completions, errors and warnings
export const SUCCESS = 'success'; // aka default
// As success, but without the tick icon
export const ALWAYS = 'always'; // aka default
// For power users. Success + generally interesting high-level information about what's happening.
// Ie, operations starting, compiler changes
export const INFO = 'info';
// For devs debugging - really detailed output about stepping into and out of major operations.
// includes lots of data dumps
export const DEBUG = 'debug';
export const ERROR = 'error';
export const WARN = 'warn';
export type LogArgs = any[];
// TODO something is wrong with these typings
// Trying to differentiate user priority presets from log functions
export type LogFns =
| 'debug'
| 'info'
| 'log'
| 'warn'
| 'error'
| 'success'
| 'always';
export type JSONLog = {
message: Array<string | object | any>;
level: LogFns;
name?: string;
time: string;
};
export type StringLog = [LogFns | 'confirm' | 'print', ...any];
export const colourize = (level: string, str: string) => {
if (typeof str === 'string') {
if (level === DEBUG) {
return c.grey(str);
}
if (level === ERROR) {
return c.red(str);
}
if (level === WARN) {
return c.yellow(str);
}
}
return str;
};
// Design for a logger
// some inputs:
// This will be passed into a job, so must look like the console object
// will be used by default by compiler and runtime
export interface Logger extends Console {
constructor(name: string): Logger;
options: Required<LogOptions>;
// standard log functions
log(...args: any[]): void;
info(...args: any[]): void;
debug(...args: any[]): void;
warn(...args: any[]): void;
error(...args: any[]): void;
success(...args: any[]): void;
always(...args: any[]): void;
// fancier log functions
proxy(obj: Partial<JSONLog>): void;
proxy(name: string, level: string, message: any[]): void;
print(...args: any[]): void;
confirm(message: string, force?: boolean): Promise<boolean>;
timer(name: string): string | undefined;
break(): void;
// group();
// groupEnd();
// time();
// timeEnd()
// special log functions
// state() // output a state object
}
// Typing here is a bit messy because filter levels and function levels are conflated
const priority: Record<LogFns | LogLevel, number> = {
[DEBUG]: 0,
[INFO]: 1,
log: 1,
default: 2,
[ALWAYS]: 2,
[WARN]: 2,
[SUCCESS]: 2,
[NONE]: 9,
[ERROR]: 100, // errors ALWAYS log
[REALLY_NONE]: 1000,
};
// // TODO I'd quite like each package to have its own colour, I think
// // that would be a nice branding exercise, even when running standalone
// const colors = {
// 'Compiler': 'green', // reassuring green
// 'Runtime': 'pink', // cheerful pink
// 'Job': 'blue', // businesslike blue
// // default to white I guess
// }
// TODO what if we want to hide levels?
// OR hide some levels?
// Or customise the display?
// TODO use cool emojis
export const styleLevel = (level: LogFns) => {
switch (level) {
case ERROR:
return c.red(symbols.cross);
case WARN:
return c.yellow(symbols.warning);
case SUCCESS:
return c.green(symbols.tick);
case ALWAYS:
return c.white(symbols.lozenge);
case DEBUG:
return c.grey(symbols.pointer);
default:
return c.white(symbols.info);
}
};
// This reporter should prefix all logs with the logger name
// It should also handle grouping
// The options object should be namespaced so that runtime managers can pass a global options object
// to each logger. Seems counter-intuitive but it should be much easier!
// TODO allow the logger to accept a single argument
export default function (name?: string, options: LogOptions = {}): Logger {
const opts = ensureOptions(options) as Required<LogOptions>;
const minLevel = priority[opts.level];
// This is what we actually pass the log strings to
const emitter = opts.logger;
const log = (name: string | undefined, level: LogFns, ...args: LogArgs) => {
if (priority[level] >= minLevel) {
if (options.json) {
logJSON(name, level, ...args);
} else {
logString(name, level, ...args);
}
}
};
const logJSON = (
name: string | undefined,
level: LogFns,
...args: LogArgs
) => {
if (args.length === 0) {
// In JSON mode, don't log empty lines
// (mostly because this spams Lightning with nonsense, but more generally
// if you have machine readable logs then "whitespace" or "formatting" logs,
// like console.break(), are meaningless)
return;
}
const message = args.map((o) =>
sanitize(o, {
stringify: false,
policy: options.sanitize,
serializeErrors: true,
})
);
if (message.length === 1 && message[0] === null) {
// Special case:
// If logging null only, don't log anything
// This enables the remove obfuscation policy to work properly
return;
}
const output: JSONLog = {
level,
name,
message,
time: hrtimestamp().toString(),
};
// Emit the output directly, without any further
// serialisation. Note that this may cause us to log
// non-serialisable stuff
emitter[level](output);
};
const logString = (
name: string | undefined,
level: LogFns,
...args: LogArgs
) => {
if (emitter.hasOwnProperty(level)) {
const cleanedArgs = args.map((o) =>
sanitize(o, {
stringify: true,
sanitizePaths: [],
policy: options.sanitize,
})
);
if (cleanedArgs.length === 1 && cleanedArgs[0] === null) {
// Special case:
// If logging null only, don't log anything
// This enables the remove obfuscation policy to work properly
return;
}
if (cleanedArgs.length) {
const output = [];
if (name && !opts.hideNamespace) {
// TODO how can we fix the with of the type column so that things
// are nicely arranged in the CLI?
output.push(c.blue(`[${name}]`));
}
if (!opts.hideIcons) {
output.push(styleLevel(level));
}
emitter[level](
...output.concat(cleanedArgs).map((s) => colourize(level, s))
);
}
}
};
// "forward" a log event from another logger as if it came from this one
const proxy = function (...args: any[]) {
let j;
if (args.length === 3) {
const [name, level, message] = args;
j = { name, level, message };
} else {
j = args[0];
}
j = j as JSONLog;
j.message ??= [];
log(j.name, j.level, ...j.message);
return [j.name, j.level, ...j.message];
};
// print() will log without any metadata/overhead/santization
// basically a proxy for console.log
const print = (...args: any[]) => {
if (opts.level !== NONE) {
if (opts.json) {
emitter.info({
message: args,
name,
time: hrtimestamp().toString(),
});
} else {
emitter.info(...args);
}
}
};
const confirm = async (message: string, force = false) => {
if (force) {
return true;
}
return iconfirm({ message });
};
const timers: Record<string, number> = {};
/**
* Toggle to start and end a timer
* If a timer is ended,returns a nicely formatted duration string
*/
const timer = (name: string) => {
if (timers[name]) {
const startTime = timers[name];
delete timers[name];
return getDurationString(new Date().getTime() - startTime);
}
timers[name] = new Date().getTime();
};
const wrap =
(level: LogFns) =>
(...args: LogArgs) =>
log(name, level, ...args);
// TODO this does not yet cover the full console API
const logger = {
info: wrap(INFO),
log: wrap(INFO),
debug: wrap(DEBUG),
error: wrap(ERROR),
warn: wrap(WARN),
success: wrap(SUCCESS),
always: wrap(ALWAYS),
confirm,
timer,
print,
proxy,
// possible convenience APIs
force: () => {}, // force the next lines to log (even if silent)
unforce: () => {}, // restore silent default
// print a line break
break: () => {
console.log();
},
indent: (_spaces: 0) => {}, // set the indent level
options: opts, // debug and testing
} as unknown; // type shenanegans
return logger as Logger;
}