-
Notifications
You must be signed in to change notification settings - Fork 5.9k
/
Copy pathlogger.ts
509 lines (457 loc) · 11.5 KB
/
logger.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
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
/**
* Log level.
*/
export enum Level {
Trace,
Debug,
Info,
Warning,
Error,
}
/**
* A field to log.
*/
export class Field<T> {
public constructor(
public readonly identifier: string,
public readonly value: T,
) { }
/**
* Convert field to JSON.
*/
public toJSON(): object {
return {
identifier: this.identifier,
value: this.value,
};
}
}
/**
* Represents the time something takes.
*/
export class Time {
public constructor(
public readonly expected: number,
public readonly ms: number,
) { }
}
// tslint:disable-next-line no-any
export type FieldArray = Array<Field<any>>;
// Same as FieldArray but supports taking an object or undefined.
// `undefined` is allowed to make it easy to conditionally display a field.
// For example: `error && field("error", error)`.
// For objects, the logger will iterate over the keys and turn them into
// instances of Field.
// tslint:disable-next-line no-any
export type LogArgument = Array<Field<any> | undefined | object>;
// Functions can be used to remove the need to perform operations when the
// logging level won't output the result anyway.
export type LogCallback = () => [string, ...LogArgument];
/**
* Creates a time field
*/
export const time = (expected: number): Time => {
return new Time(expected, Date.now());
};
export const field = <T>(name: string, value: T): Field<T> => {
return new Field(name, value);
};
export type Extender = (msg: {
message: string,
level: Level,
type: "trace" | "info" | "warn" | "debug" | "error",
fields?: FieldArray,
section?: string,
}) => void;
/**
* This formats & builds text for logging.
* It should only be used to build one log item at a time since it stores the
* currently built items and appends to that.
*/
export abstract class Formatter {
protected format = "";
protected args = <string[]>[];
/**
* Add a tag.
*/
public abstract tag(name: string, color: string): void;
/**
* Add string variable.
*/
public abstract push(arg: string, color?: string, weight?: string): void;
/**
* Add arbitrary variable.
*/
public abstract push(arg: any): void; // tslint:disable-line no-any
/**
* Add fields.
*/
// tslint:disable-next-line no-any
public abstract fields(fields: FieldArray): void;
/**
* Flush out the built arguments.
*/
public flush(): any[] { // tslint:disable-line no-any
const args = [this.format, ...this.args];
this.format = "";
this.args = [];
return args;
}
/**
* Get the format string for the value type.
*/
protected getType(arg: any): string { // tslint:disable-line no-any
switch (typeof arg) {
case "object":
return "%o";
case "number":
return "%d";
default:
return "%s";
}
}
}
/**
* Browser formatter.
*/
export class BrowserFormatter extends Formatter {
/**
* Add a tag.
*/
public tag(name: string, color: string): void {
this.format += `%c ${name} `;
this.args.push(
`border: 1px solid #222; background-color: ${color}; padding-top: 1px;`
+ " padding-bottom: 1px; font-size: 12px; font-weight: bold; color: white;"
+ (name.length === 4 ? "padding-left: 3px; padding-right: 4px;" : ""),
);
// A space to separate the tag from the title.
this.push(" ");
}
/**
* Add an argument.
*/
public push(arg: any, color: string = "inherit", weight: string = "normal"): void { // tslint:disable-line no-any
if (color || weight) {
this.format += "%c";
this.args.push(
(color ? `color: ${color};` : "") +
(weight ? `font-weight: ${weight};` : ""),
);
}
this.format += this.getType(arg);
this.args.push(arg);
}
/**
* Add fields.
*/
// tslint:disable-next-line no-any
public fields(fields: FieldArray): void {
// tslint:disable-next-line no-console
console.groupCollapsed(...this.flush());
fields.forEach((field) => {
this.push(field.identifier, "#3794ff", "bold");
if (typeof field.value !== "undefined" && field.value.constructor && field.value.constructor.name) {
this.push(` (${field.value.constructor.name})`);
}
this.push(": ");
this.push(field.value);
// tslint:disable-next-line no-console
console.log(...this.flush());
});
// tslint:disable-next-line no-console
console.groupEnd();
}
}
/**
* Server (Node) formatter.
*/
export class ServerFormatter extends Formatter {
/**
* Add a tag.
*/
public tag(name: string, color: string): void {
const [r, g, b] = this.hexToRgb(color);
while (name.length < 5) {
name += " ";
}
this.format += "\u001B[1m";
this.format += `\u001B[38;2;${r};${g};${b}m${name} \u001B[0m`;
}
/**
* Add an argument.
*/
public push(arg: any, color?: string, weight?: string): void { // tslint:disable-line no-any
if (weight === "bold") {
this.format += "\u001B[1m";
}
if (color) {
const [r, g, b] = this.hexToRgb(color);
this.format += `\u001B[38;2;${r};${g};${b}m`;
}
this.format += this.getType(arg);
if (weight || color) {
this.format += "\u001B[0m";
}
this.args.push(arg);
}
/**
* Add fields.
*/
// tslint:disable-next-line no-any
public fields(fields: FieldArray): void {
// tslint:disable-next-line no-any
const obj: { [key: string]: any} = {};
this.format += "\u001B[38;2;140;140;140m";
fields.forEach((field) => {
obj[field.identifier] = field.value;
});
this.args.push(JSON.stringify(obj));
console.log(...this.flush()); // tslint:disable-line no-console
}
/**
* Convert fully-formed hex to rgb.
*/
private hexToRgb(hex: string): [number, number, number] {
const integer = parseInt(hex.substr(1), 16);
return [
(integer >> 16) & 0xFF,
(integer >> 8) & 0xFF,
integer & 0xFF,
];
}
}
/**
* Class for logging.
*/
export class Logger {
public level = Level.Info;
private readonly nameColor?: string;
private muted: boolean = false;
public constructor(
private _formatter: Formatter,
private readonly name?: string,
private readonly defaultFields?: FieldArray,
private readonly extenders: Extender[] = [],
) {
if (name) {
this.nameColor = this.hashStringToColor(name);
}
const envLevel = typeof global !== "undefined" && typeof global.process !== "undefined" ? global.process.env.LOG_LEVEL : process.env.LOG_LEVEL;
if (envLevel) {
switch (envLevel) {
case "trace": this.level = Level.Trace; break;
case "debug": this.level = Level.Debug; break;
case "info": this.level = Level.Info; break;
case "warn": this.level = Level.Warning; break;
case "error": this.level = Level.Error; break;
}
}
}
public set formatter(formatter: Formatter) {
this._formatter = formatter;
}
/**
* Supresses all output
*/
public mute(): void {
this.muted = true;
}
/**
* Extend the logger (for example to send the logs elsewhere).
*/
public extend(extender: Extender): void {
this.extenders.push(extender);
}
/**
* Log information.
*/
public info(fn: LogCallback): void;
public info(message: string, ...args: LogArgument): void;
public info(message: LogCallback | string, ...args: LogArgument): void {
this.handle({
type: "info",
message,
args,
tagColor: "#008FBF",
level: Level.Info,
});
}
/**
* Log a warning.
*/
public warn(fn: LogCallback): void;
public warn(message: string, ...args: LogArgument): void;
public warn(message: LogCallback | string, ...args: LogArgument): void {
this.handle({
type: "warn",
message,
args,
tagColor: "#FF9D00",
level: Level.Warning,
});
}
/**
* Log a trace message.
*/
public trace(fn: LogCallback): void;
public trace(message: string, ...args: LogArgument): void;
public trace(message: LogCallback | string, ...args: LogArgument): void {
this.handle({
type: "trace",
message,
args,
tagColor: "#888888",
level: Level.Trace,
});
}
/**
* Log a debug message.
*/
public debug(fn: LogCallback): void;
public debug(message: string, ...args: LogArgument): void;
public debug(message: LogCallback | string, ...args: LogArgument): void {
this.handle({
type: "debug",
message,
args,
tagColor: "#84009E",
level: Level.Debug,
});
}
/**
* Log an error.
*/
public error(fn: LogCallback): void;
public error(message: string, ...args: LogArgument): void;
public error(message: LogCallback | string, ...args: LogArgument): void {
this.handle({
type: "error",
message,
args,
tagColor: "#B00000",
level: Level.Error,
});
}
/**
* Returns a sub-logger with a name.
* Each name is deterministically generated a color.
*/
public named(name: string, ...fields: FieldArray): Logger {
const l = new Logger(this._formatter, name, fields, this.extenders);
if (this.muted) {
l.mute();
}
return l;
}
/**
* Log a message.
*/
private handle(options: {
type: "trace" | "info" | "warn" | "debug" | "error";
message: string | LogCallback;
args?: LogArgument;
level: Level;
tagColor: string;
}): void {
if (this.level > options.level || this.muted) {
return;
}
if (typeof options.message === "function") {
const values = options.message();
options.message = values.shift() as string;
options.args = values as FieldArray;
}
const fields: FieldArray = [];
if (options.args) {
options.args.forEach((arg) => {
if (arg instanceof Field) {
fields.push(arg);
} else if (arg) {
Object.keys(arg).forEach((k) => {
// tslint:disable-next-line no-any
fields.push(field(k, (arg as any)[k]));
});
}
});
}
if (this.defaultFields) {
fields.push(...this.defaultFields);
}
const now = Date.now();
let times: Array<Field<Time>> = [];
const hasFields = fields && fields.length > 0;
if (hasFields) {
times = fields.filter((f) => f.value instanceof Time);
}
this._formatter.tag(options.type.toUpperCase(), options.tagColor);
if (this.name && this.nameColor) {
this._formatter.tag(this.name.toUpperCase(), this.nameColor);
}
this._formatter.push(options.message);
if (times.length > 0) {
times.forEach((time) => {
const diff = now - time.value.ms;
const expPer = diff / time.value.expected;
const min = 125 * (1 - expPer);
const max = 125 + min;
const green = expPer < 1 ? max : min;
const red = expPer >= 1 ? max : min;
this._formatter.push(` ${time.identifier}=`, "#3794ff");
this._formatter.push(`${diff}ms`, this.rgbToHex(red > 0 ? red : 0, green > 0 ? green : 0, 0));
});
}
// tslint:disable no-console
if (hasFields) {
this._formatter.fields(fields);
} else {
console.log(...this._formatter.flush());
}
// tslint:enable no-console
this.extenders.forEach((extender) => {
extender({
section: this.name,
fields,
level: options.level,
message: options.message as string,
type: options.type,
});
});
}
/**
* Hashes a string.
*/
private djb2(str: string): number {
let hash = 5381;
for (let i = 0; i < str.length; i++) {
hash = ((hash << 5) + hash) + str.charCodeAt(i); /* hash * 33 + c */
}
return hash;
}
/**
* Convert rgb to hex.
*/
private rgbToHex(r: number, g: number, b: number): string {
const integer = ((Math.round(r) & 0xFF) << 16)
+ ((Math.round(g) & 0xFF) << 8)
+ (Math.round(b) & 0xFF);
const str = integer.toString(16);
return "#" + "000000".substring(str.length) + str;
}
/**
* Generates a deterministic color from a string using hashing.
*/
private hashStringToColor(str: string): string {
const hash = this.djb2(str);
return this.rgbToHex(
(hash & 0xFF0000) >> 16,
(hash & 0x00FF00) >> 8,
hash & 0x0000FF,
);
}
}
export const logger = new Logger(
typeof process === "undefined" || typeof process.stdout === "undefined"
? new BrowserFormatter()
: new ServerFormatter(),
);