forked from spy4x/seed
-
Notifications
You must be signed in to change notification settings - Fork 0
/
log.service.ts
278 lines (249 loc) · 7.69 KB
/
log.service.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
import { inspect as utilInspect } from 'util';
import * as chalk from 'chalk';
import { format } from 'date-fns';
import { isEnv } from '../../constants';
import { Environment } from '@seed/shared/types';
export enum LogSeverity {
log = 'log',
warn = 'warn',
error = 'error',
}
export enum LogContext {
startSegment = 'startSegment',
finishSegment = 'finishSegment',
}
type Params = unknown;
enum LogArgType {
regular = 'regular',
subCaller = 'subCaller',
inspect = 'inspect',
}
interface LogArg {
type: LogArgType;
value: unknown;
}
const IS_PRODUCTION = isEnv(Environment.production);
export function chalkify(str: string, chalkModifier: chalk.Chalk): string {
if (IS_PRODUCTION) {
return str;
}
return chalkModifier(` ${str} `);
}
export class LogSegment {
constructor(public caller: string, public startDate: Date, private readonly logger: LogService) {}
log(message: string, params?: Params, context?: LogContext): this {
const args: LogArg[] = [];
args.push({ type: LogArgType.subCaller, value: this.caller });
args.push({ type: LogArgType.regular, value: message });
if (params) {
args.push({ type: LogArgType.inspect, value: params });
}
this.logger.write(LogSeverity.log, args, context);
return this;
}
warn(message: string, params?: Params, context?: LogContext): this {
const args: LogArg[] = [];
args.push({ type: LogArgType.subCaller, value: this.caller });
args.push({ type: LogArgType.regular, value: message });
if (params) {
args.push({ type: LogArgType.inspect, value: params });
}
this.logger.write(LogSeverity.warn, args, context);
return this;
}
error({
message,
error,
params,
context,
}: {
message?: string;
error?: Error;
params?: Params;
context?: LogContext;
}): this {
const args: LogArg[] = [];
args.push({ type: LogArgType.subCaller, value: this.caller });
if (message) {
args.push({ type: LogArgType.regular, value: message });
}
if (error) {
args.push({ type: LogArgType.regular, value: error });
}
if (params) {
args.push({ type: LogArgType.inspect, value: params });
}
this.logger.write(LogSeverity.error, args, context);
return this;
}
endWithSuccess(params?: Params): this {
const finish = new Date();
const durationMs = finish.getTime() - this.startDate.getTime();
const durationStr = `${durationMs}ms`;
return this.log(`Completed in ${chalkify(durationStr, chalk.bgWhite.black)}`, params, LogContext.finishSegment);
}
endWithFail(error: Error, params?: Params): this {
const finish = new Date();
const durationMs = finish.getTime() - this.startDate.getTime();
const paramsObj: { durationMs: number; params?: Params } = { durationMs };
if (params) {
paramsObj.params = params;
}
return this.error({
message: `Error`,
error,
params: paramsObj,
context: LogContext.finishSegment,
});
}
}
export class LogService {
constructor(public caller: string) {}
public static inspect(object: unknown): string {
const MAX_LINE_WIDTH = 120;
return utilInspect(object, {
depth: 15, // deep nesting, but avoid infinity for security reasons
colors: !IS_PRODUCTION, // Google Cloud Logger shows colors as special symbols, like "[32m", instead of coloring text
breakLength: IS_PRODUCTION ? Infinity : MAX_LINE_WIDTH,
});
}
public static getIcon(severity: LogSeverity, context?: LogContext): string {
if (severity === LogSeverity.error) {
return '⛔️';
}
if (severity === LogSeverity.warn) {
return '⚠️ ';
}
switch (context) {
case LogContext.startSegment:
return '▶️ ';
case LogContext.finishSegment:
return '✅';
case undefined:
return '🔷';
}
return '❓';
}
setCaller(caller: string): this {
this.caller = caller;
return this;
}
startSegment(name: string, params?: Params): LogSegment {
const segment = new LogSegment(name, new Date(), this);
segment.log(`Started`, params, LogContext.startSegment);
return segment;
}
async trackSegment<R>(
name: string,
fn: (logSegment: LogSegment) => Promise<R>,
params?: Params,
shouldLogResult?: boolean,
): Promise<R> {
const segment = new LogSegment(name, new Date(), this);
segment.log(`Started`, params, LogContext.startSegment);
try {
const result = await fn(segment);
if (shouldLogResult) {
segment.endWithSuccess(result);
} else {
segment.endWithSuccess();
}
return result;
} catch (error: unknown) {
if (error instanceof Error) {
segment.endWithFail(error);
}
throw error;
}
}
trackSegmentSync<R>(name: string, fn: (logSegment: LogSegment) => R, params?: Params, shouldLogResult?: boolean): R {
const segment = new LogSegment(name, new Date(), this);
segment.log(`Started`, params, LogContext.startSegment);
try {
const result = fn(segment);
if (shouldLogResult) {
segment.endWithSuccess(result);
} else {
segment.endWithSuccess();
}
return result;
} catch (error: unknown) {
if (error instanceof Error) {
segment.endWithFail(error);
}
throw error;
}
}
log(message?: string, params?: Params): this {
const args: LogArg[] = [];
if (message) {
args.push({ type: LogArgType.regular, value: message });
}
if (params) {
args.push({ type: LogArgType.inspect, value: params });
}
return this.write(LogSeverity.log, args);
}
warn(message?: string, params?: Params): this {
const args: LogArg[] = [];
if (message) {
args.push({ type: LogArgType.regular, value: message });
}
if (params) {
args.push({ type: LogArgType.inspect, value: params });
}
return this.write(LogSeverity.warn, args);
}
error({ message, error, params }: { message?: string; error?: Error; params?: Params }): this {
const args: LogArg[] = [];
if (message) {
args.push({ type: LogArgType.regular, value: message });
}
if (error) {
args.push({ type: LogArgType.regular, value: error });
}
if (params) {
args.push({ type: LogArgType.inspect, value: params });
}
return this.write(LogSeverity.error, args);
}
write(severity: LogSeverity, args: LogArg[], context?: LogContext): this {
let logArgs: unknown[] = [];
if (!IS_PRODUCTION) {
const timestamp = format(new Date(), 'HH:mm:ss.SSS');
logArgs.push(chalkify(timestamp, chalk.grey));
}
const maxLength = 20;
const brown = { r: 180, g: 150, b: 100 };
const purple = { r: 150, g: 125, b: 210 };
const spaceCharacter = IS_PRODUCTION ? '_' : ' ';
let callerStr = chalkify(this.caller.padStart(maxLength, spaceCharacter), chalk.rgb(brown.r, brown.g, brown.b));
const subCaller = args.find(i => i.type === 'subCaller');
if (subCaller) {
callerStr += ` > ${chalkify(
(subCaller.value as string).padEnd(maxLength, spaceCharacter),
chalk.rgb(purple.r, purple.g, purple.b),
)}`;
}
logArgs.push(callerStr);
logArgs.push(LogService.getIcon(severity, context));
logArgs = [
...logArgs,
...args
.filter(i => i.type !== 'subCaller')
.map(arg => {
switch (arg.type) {
case 'regular':
return arg.value;
case 'inspect':
return LogService.inspect(arg.value);
default:
throw new Error(`LogService.write(): Unknown argument type ${arg.type}`);
}
}),
];
// eslint-disable-next-line no-console
console[severity](...logArgs);
return this;
}
}