forked from gremo/nest-winston
-
Notifications
You must be signed in to change notification settings - Fork 0
/
winston.utilities.ts
74 lines (66 loc) · 2.5 KB
/
winston.utilities.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
import { Format } from 'logform';
import { NestLikeConsoleFormatOptions } from './winston.interfaces';
import { format } from 'winston';
import { inspect } from 'util';
import safeStringify from 'fast-safe-stringify';
const clc = {
bold: (text: string) => `\x1B[1m${text}\x1B[0m`,
green: (text: string) => `\x1B[32m${text}\x1B[39m`,
yellow: (text: string) => `\x1B[33m${text}\x1B[39m`,
red: (text: string) => `\x1B[31m${text}\x1B[39m`,
magentaBright: (text: string) => `\x1B[95m${text}\x1B[39m`,
cyanBright: (text: string) => `\x1B[96m${text}\x1B[39m`,
};
const nestLikeColorScheme: Record<string, (text: string) => string> = {
log: clc.green,
error: clc.red,
warn: clc.yellow,
debug: clc.magentaBright,
verbose: clc.cyanBright,
};
const nestLikeConsoleFormat = (
appName = 'NestWinston',
options: NestLikeConsoleFormatOptions = {
colors: !process.env.NO_COLOR,
prettyPrint: false,
},
): Format =>
format.printf(({ context, level, timestamp, message, ms, ...meta }) => {
if ('info' === level) {
level = 'log';
}
if ('undefined' !== typeof timestamp) {
// Only format the timestamp to a locale representation if it's ISO 8601 format. Any format
// that is not a valid date string will throw, just ignore it (it will be printed as-is).
try {
if (timestamp === new Date(timestamp).toISOString()) {
timestamp = new Date(timestamp).toLocaleString();
}
} catch (error) {
// eslint-disable-next-line no-empty
}
}
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
const color = options.colors && nestLikeColorScheme[level] || ((text: string): string => text);
const yellow = options.colors ? clc.yellow : ((text: string): string => text);
const stringifiedMeta = safeStringify(meta);
const formattedMeta = options.prettyPrint
? inspect(JSON.parse(stringifiedMeta), { colors: options.colors, depth: null })
: stringifiedMeta;
return (
color(`[${appName}] ${String(process.pid).padEnd(6)} - `) +
('undefined' !== typeof timestamp ? `${timestamp} ` : '') +
`${color(level.toUpperCase().padStart(7))}\t` +
('undefined' !== typeof context
? `${yellow('[' + context + ']')} `
: '') +
`${color(message)}` +
(formattedMeta && formattedMeta !== '{}' ? ` - ${formattedMeta}` : '') +
('undefined' !== typeof ms ? ` ${yellow(ms)}` : '')
);
});
export const utilities = {
format: {
nestLike: nestLikeConsoleFormat,
},
};