-
Notifications
You must be signed in to change notification settings - Fork 135
/
Copy pathLogger.ts
61 lines (53 loc) · 2.04 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
/* eslint-disable @typescript-eslint/no-explicit-any */
const GET_AGENT_LOG_PREFIX = 'FDC3 getAgent: ';
//check if color is supported in console;
let noColor = true;
//else only occurs in a browser and can't be tested in node
/* istanbul ignore if */
if (typeof process !== 'undefined') {
const argv = process.argv || /* istanbul ignore next */ [];
const env = process.env || /* istanbul ignore next */ {};
noColor =
(!!env.NO_COLOR || argv.includes('--no-color')) &&
!(
!!env.FORCE_COLOR ||
argv.includes('--color') ||
process.platform === 'win32' /* istanbul ignore next */ ||
((process.stdout || {}).isTTY && env.TERM !== 'dumb') ||
/* istanbul ignore next */ !!env.CI
);
}
type ColorFn = (aString: string) => string;
const debugColor: ColorFn = value => (noColor ? value : '\x1b[30m\x1b[2m' + value + '\x1b[22m\x1b[39m');
const logColor: ColorFn = value => (noColor ? value : '\x1b[32m\x1b[2m' + value + '\x1b[22m\x1b[39m');
const warnColor: ColorFn = value => (noColor ? value : '\x1b[33m' + value + '\x1b[39m');
const errorColor: ColorFn = value => (noColor ? value : '\x1b[31m' + value + '\x1b[39m');
const prefixAndColorize = (params: any[], colorFn: ColorFn): string[] => {
const prefixed = [GET_AGENT_LOG_PREFIX, ...params];
return prefixed.map(value => {
if (typeof value === 'string') {
//just color strings
return colorFn(value);
} else if (value && value.stack && value.message) {
//probably an error
return colorFn(value.stack);
} else {
//something else... lets hope it stringifies
return colorFn(JSON.stringify(value, null, 2));
}
});
};
export class Logger {
static debug(...params: any[]) {
console.debug(...prefixAndColorize(params, debugColor));
}
static log(...params: any[]) {
console.log(...prefixAndColorize(params, logColor));
}
static warn(...params: any[]) {
console.warn(...prefixAndColorize(params, warnColor));
}
static error(...params: any[]) {
console.error(...prefixAndColorize(params, errorColor));
}
}