-
Notifications
You must be signed in to change notification settings - Fork 0
/
logReporter.ts
59 lines (50 loc) · 1.68 KB
/
logReporter.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
import { ConsolaLogObject, ConsolaReporter, FancyReporter, ReporterOptions } from 'consola';
import chalk = require('chalk');
import * as figures from 'figures';
import type { Chalk, BackgroundColor, ForegroundColor } from 'chalk';
import { Nullable } from 'Union/Nullable';
import { isNumber } from 'ts-type-guards';
const bgColorCache: Record<string, Chalk> = {};
const chalkBgColor = (name: BGColor): Chalk => {
if (!bgColorCache[name]) {
bgColorCache[name] = chalk[name];
}
return bgColorCache[name];
};
const LEVEL_COLOR_MAP: Record<number, Nullable<BGColor>> = {
0: `bgRed`,
1: `bgYellow`,
2: `bgWhite`,
3: `bgGreen`,
};
const TYPE_COLOR_MAP: Record<string, Nullable<BGColor>> = {
info: `bgBlue`,
};
const TYPE_ICONS: Record<string, Nullable<string>> = {
info: figures(`ℹ`),
success: figures(`✔`),
error: figures(`✖`),
warn: figures(`Ⓘ`),
};
export type BGColor = typeof BackgroundColor;
export type Color = typeof ForegroundColor;
export interface LogReporterOptions extends ReporterOptions {
secondaryColor: Color;
bgColor: BGColor;
}
export class LogReporter extends FancyReporter implements ConsolaReporter {
private bgColor: BGColor;
constructor(options: LogReporterOptions) {
super(options);
this.bgColor = options.bgColor;
}
protected formatType(logObj: ConsolaLogObject): string {
const typeColor =
(logObj.type && TYPE_COLOR_MAP[logObj.type]) ||
(isNumber(logObj.level) && LEVEL_COLOR_MAP[logObj.level]) ||
this.bgColor;
const typeIcon = logObj.type && TYPE_ICONS[logObj.type];
const text = ` ${typeIcon || (logObj.type && logObj.type.toUpperCase())} `;
return chalkBgColor(typeColor).black(text);
}
}