-
-
Notifications
You must be signed in to change notification settings - Fork 7.8k
/
Copy pathlogger.service.ts
376 lines (331 loc) · 10 KB
/
logger.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
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
import { Injectable, Optional } from '../decorators/core';
import { isObject } from '../utils/shared.utils';
import { ConsoleLogger } from './console-logger.service';
import { isLogLevelEnabled } from './utils';
const LOG_LEVELS = [
'verbose',
'debug',
'log',
'warn',
'error',
'fatal',
] as const satisfies string[];
/**
* @publicApi
*/
export type LogLevel = (typeof LOG_LEVELS)[number];
/**
* @publicApi
*/
export function isLogLevel(maybeLogLevel: any): maybeLogLevel is LogLevel {
return LOG_LEVELS.includes(maybeLogLevel);
}
/**
* @publicApi
*/
export function filterLogLevels(parseableString = ''): LogLevel[] {
const sanitizedSring = parseableString.replaceAll(' ', '').toLowerCase();
if (sanitizedSring[0] === '>') {
const orEqual = sanitizedSring[1] === '=';
const logLevelIndex = (LOG_LEVELS as string[]).indexOf(
sanitizedSring.substring(orEqual ? 2 : 1),
);
if (logLevelIndex === -1) {
throw new Error(`parse error (unknown log level): ${sanitizedSring}`);
}
return LOG_LEVELS.slice(orEqual ? logLevelIndex : logLevelIndex + 1);
} else if (sanitizedSring.includes(',')) {
return sanitizedSring.split(',').filter(isLogLevel);
}
return isLogLevel(sanitizedSring) ? [sanitizedSring] : LOG_LEVELS;
}
/**
* @publicApi
*/
export interface LoggerService {
/**
* Write a 'log' level log.
*/
log(message: any, ...optionalParams: any[]): any;
/**
* Write an 'error' level log.
*/
error(message: any, ...optionalParams: any[]): any;
/**
* Write a 'warn' level log.
*/
warn(message: any, ...optionalParams: any[]): any;
/**
* Write a 'debug' level log.
*/
debug?(message: any, ...optionalParams: any[]): any;
/**
* Write a 'verbose' level log.
*/
verbose?(message: any, ...optionalParams: any[]): any;
/**
* Write a 'fatal' level log.
*/
fatal?(message: any, ...optionalParams: any[]): any;
/**
* Set log levels.
* @param levels log levels
*/
setLogLevels?(levels: LogLevel[]): any;
}
interface LogBufferRecord {
/**
* Method to execute.
*/
methodRef: Function;
/**
* Arguments to pass to the method.
*/
arguments: unknown[];
}
const DEFAULT_LOGGER = new ConsoleLogger();
const dateTimeFormatter = new Intl.DateTimeFormat(undefined, {
year: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
day: '2-digit',
month: '2-digit',
});
/**
* @publicApi
*/
@Injectable()
export class Logger implements LoggerService {
protected static logBuffer = new Array<LogBufferRecord>();
protected static staticInstanceRef?: LoggerService = DEFAULT_LOGGER;
protected static logLevels?: LogLevel[];
private static isBufferAttached: boolean;
protected localInstanceRef?: LoggerService;
private static WrapBuffer: MethodDecorator = (
target: object,
propertyKey: string | symbol,
descriptor: TypedPropertyDescriptor<any>,
) => {
const originalFn = descriptor.value;
descriptor.value = function (...args: unknown[]) {
if (Logger.isBufferAttached) {
Logger.logBuffer.push({
methodRef: originalFn.bind(this),
arguments: args,
});
return;
}
return originalFn.call(this, ...args);
};
};
constructor();
constructor(context: string);
constructor(context: string, options?: { timestamp?: boolean });
constructor(
@Optional() protected context?: string,
@Optional() protected options: { timestamp?: boolean } = {},
) {}
get localInstance(): LoggerService {
if (Logger.staticInstanceRef === DEFAULT_LOGGER) {
return this.registerLocalInstanceRef();
} else if (Logger.staticInstanceRef instanceof Logger) {
const prototype = Object.getPrototypeOf(Logger.staticInstanceRef);
if (prototype.constructor === Logger) {
return this.registerLocalInstanceRef();
}
}
return Logger.staticInstanceRef!;
}
/**
* Write an 'error' level log.
*/
error(message: any, stack?: string, context?: string): void;
error(message: any, ...optionalParams: [...any, string?, string?]): void;
@Logger.WrapBuffer
error(message: any, ...optionalParams: any[]) {
optionalParams = this.context
? (optionalParams.length ? optionalParams : [undefined]).concat(
this.context,
)
: optionalParams;
this.localInstance?.error(message, ...optionalParams);
}
/**
* Write a 'log' level log.
*/
log(message: any, context?: string): void;
log(message: any, ...optionalParams: [...any, string?]): void;
@Logger.WrapBuffer
log(message: any, ...optionalParams: any[]) {
optionalParams = this.context
? optionalParams.concat(this.context)
: optionalParams;
this.localInstance?.log(message, ...optionalParams);
}
/**
* Write a 'warn' level log.
*/
warn(message: any, context?: string): void;
warn(message: any, ...optionalParams: [...any, string?]): void;
@Logger.WrapBuffer
warn(message: any, ...optionalParams: any[]) {
optionalParams = this.context
? optionalParams.concat(this.context)
: optionalParams;
this.localInstance?.warn(message, ...optionalParams);
}
/**
* Write a 'debug' level log.
*/
debug(message: any, context?: string): void;
debug(message: any, ...optionalParams: [...any, string?]): void;
@Logger.WrapBuffer
debug(message: any, ...optionalParams: any[]) {
optionalParams = this.context
? optionalParams.concat(this.context)
: optionalParams;
this.localInstance?.debug?.(message, ...optionalParams);
}
/**
* Write a 'verbose' level log.
*/
verbose(message: any, context?: string): void;
verbose(message: any, ...optionalParams: [...any, string?]): void;
@Logger.WrapBuffer
verbose(message: any, ...optionalParams: any[]) {
optionalParams = this.context
? optionalParams.concat(this.context)
: optionalParams;
this.localInstance?.verbose?.(message, ...optionalParams);
}
/**
* Write a 'fatal' level log.
*/
fatal(message: any, context?: string): void;
fatal(message: any, ...optionalParams: [...any, string?]): void;
@Logger.WrapBuffer
fatal(message: any, ...optionalParams: any[]) {
optionalParams = this.context
? optionalParams.concat(this.context)
: optionalParams;
this.localInstance?.fatal?.(message, ...optionalParams);
}
/**
* Write an 'error' level log.
*/
static error(message: any, stackOrContext?: string): void;
static error(message: any, context?: string): void;
static error(message: any, stack?: string, context?: string): void;
static error(
message: any,
...optionalParams: [...any, string?, string?]
): void;
@Logger.WrapBuffer
static error(message: any, ...optionalParams: any[]) {
this.staticInstanceRef?.error(message, ...optionalParams);
}
/**
* Write a 'log' level log.
*/
static log(message: any, context?: string): void;
static log(message: any, ...optionalParams: [...any, string?]): void;
@Logger.WrapBuffer
static log(message: any, ...optionalParams: any[]) {
this.staticInstanceRef?.log(message, ...optionalParams);
}
/**
* Write a 'warn' level log.
*/
static warn(message: any, context?: string): void;
static warn(message: any, ...optionalParams: [...any, string?]): void;
@Logger.WrapBuffer
static warn(message: any, ...optionalParams: any[]) {
this.staticInstanceRef?.warn(message, ...optionalParams);
}
/**
* Write a 'debug' level log, if the configured level allows for it.
* Prints to `stdout` with newline.
*/
static debug(message: any, context?: string): void;
static debug(message: any, ...optionalParams: [...any, string?]): void;
@Logger.WrapBuffer
static debug(message: any, ...optionalParams: any[]) {
this.staticInstanceRef?.debug?.(message, ...optionalParams);
}
/**
* Write a 'verbose' level log.
*/
static verbose(message: any, context?: string): void;
static verbose(message: any, ...optionalParams: [...any, string?]): void;
@Logger.WrapBuffer
static verbose(message: any, ...optionalParams: any[]) {
this.staticInstanceRef?.verbose?.(message, ...optionalParams);
}
/**
* Write a 'fatal' level log.
*/
static fatal(message: any, context?: string): void;
static fatal(message: any, ...optionalParams: [...any, string?]): void;
@Logger.WrapBuffer
static fatal(message: any, ...optionalParams: any[]) {
this.staticInstanceRef?.fatal?.(message, ...optionalParams);
}
/**
* Print buffered logs and detach buffer.
*/
static flush() {
this.isBufferAttached = false;
this.logBuffer.forEach(item =>
item.methodRef(...(item.arguments as [string])),
);
this.logBuffer = [];
}
/**
* Attach buffer.
* Turns on initialization logs buffering.
*/
static attachBuffer() {
this.isBufferAttached = true;
}
/**
* Detach buffer.
* Turns off initialization logs buffering.
*/
static detachBuffer() {
this.isBufferAttached = false;
}
static getTimestamp() {
return dateTimeFormatter.format(Date.now());
}
static overrideLogger(logger: LoggerService | LogLevel[] | boolean) {
if (Array.isArray(logger)) {
Logger.logLevels = logger;
return this.staticInstanceRef?.setLogLevels?.(logger);
}
if (isObject(logger)) {
if (logger instanceof Logger && logger.constructor !== Logger) {
const errorMessage = `Using the "extends Logger" instruction is not allowed in Nest v9. Please, use "extends ConsoleLogger" instead.`;
this.staticInstanceRef?.error(errorMessage);
throw new Error(errorMessage);
}
this.staticInstanceRef = logger as LoggerService;
} else {
this.staticInstanceRef = undefined;
}
}
static isLevelEnabled(level: LogLevel): boolean {
const logLevels = Logger.logLevels;
return isLogLevelEnabled(level, logLevels);
}
private registerLocalInstanceRef() {
if (this.localInstanceRef) {
return this.localInstanceRef;
}
this.localInstanceRef = new ConsoleLogger(this.context!, {
timestamp: this.options?.timestamp,
logLevels: Logger.logLevels,
});
return this.localInstanceRef;
}
}