-
Notifications
You must be signed in to change notification settings - Fork 153
/
Copy pathLogger.ts
666 lines (592 loc) · 18.8 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
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
import type { Context } from 'aws-lambda';
import { LogFormatterInterface, PowertoolLogFormatter } from './formatter';
import { LogItem } from './log';
import cloneDeep from 'lodash.clonedeep';
import merge from 'lodash.merge';
import { ConfigServiceInterface, EnvironmentVariablesService } from './config';
import type {
ClassThatLogs,
Environment,
HandlerMethodDecorator,
LambdaFunctionContext,
LogAttributes,
LoggerOptions,
LogItemExtraInput,
LogItemMessage,
LogLevel,
LogLevelThresholds,
PowertoolLogData,
} from './types';
/**
*
* # Logger class
*
* ## Intro
*
* The Logger utility provides an opinionated logger with output structured as JSON.
*
* ## Key features
*
* - Capture key fields from Lambda context, cold start and structures logging output as JSON
* - Log Lambda context when instructed (disabled by default)
* - Log sampling prints all logs for a percentage of invocations (disabled by default)
* - Append additional keys to structured log at any point in time
*
* ## Basic usage
*
* import { Logger } from "@aws-lambda-powertools/logger";
* const logger = new Logger();
*
* @class
* @implements {ClassThatLogs}
* @see https://awslabs.github.io/aws-lambda-powertools-typescript/latest/core/logger/
*/
class Logger implements ClassThatLogs {
private static coldStart?: boolean = undefined;
private static coldStartEvaluated: boolean = false;
private customConfigService?: ConfigServiceInterface;
private static readonly defaultLogLevel: LogLevel = 'INFO';
private static readonly defaultServiceName: string = 'service_undefined';
private envVarsService?: EnvironmentVariablesService;
private logFormatter?: LogFormatterInterface;
private logLevel?: LogLevel;
private readonly logLevelThresholds: LogLevelThresholds = {
DEBUG: 8,
INFO: 12,
WARN: 16,
ERROR: 20,
};
private logsSampled: boolean = false;
private persistentLogAttributes?: LogAttributes = {};
private powertoolLogData: PowertoolLogData = <PowertoolLogData>{};
/**
* It initializes the Logger class with an optional set of options (settings).
* *
* @param {LoggerOptions} options
*/
public constructor(options: LoggerOptions = {}) {
this.setOptions(options);
}
/**
* It adds the current Lambda function's invocation context data to the powertoolLogData propriety of the instance.
* This context data will be part of all printed log items.
*
* @param {Context} context
* @returns {void}
*/
public addContext(context: Context): void {
Logger.evaluateColdStartOnce();
const lambdaContext: Partial<LambdaFunctionContext> = {
invokedFunctionArn: context.invokedFunctionArn,
coldStart: Logger.getColdStartValue(),
awsRequestId: context.awsRequestId,
memoryLimitInMB: Number(context.memoryLimitInMB),
functionName: context.functionName,
functionVersion: context.functionVersion,
};
this.addToPowertoolLogData({
lambdaContext,
});
}
/**
* it adds the given attributes (key-value pairs) to all log items generated by this Logger instance.
*
* @param {LogAttributes} attributes
* @returns {void}
*/
public addPersistentLogAttributes(attributes?: LogAttributes): void {
this.persistentLogAttributes = merge(attributes, this.getPersistentLogAttributes());
}
/**
* Alias for addPersistentLogAttributes.
*
* @param {LogAttributes} attributes
* @returns {void}
*/
public appendKeys(attributes?: LogAttributes): void {
this.addPersistentLogAttributes(attributes);
}
/**
* it creates a separate Logger instance, identical to the current one.
* It's possible to overwrite the new instance options by passing them.
*
* @param {LoggerOptions} options
* @returns {Logger}
*/
public createChild(options: LoggerOptions = {}): Logger {
return cloneDeep(this).setOptions(options);
}
/**
* It prints a log item with level DEBUG.
*
* @param {LogItemMessage} input
* @param {Error | LogAttributes | unknown} extraInput
* @returns {void}
*/
public debug(input: LogItemMessage, ...extraInput: LogItemExtraInput): void {
this.processLogItem('DEBUG', input, extraInput);
}
/**
* It prints a log item with level ERROR.
*
* @param {LogItemMessage} input
* @param {Error | LogAttributes | unknown} extraInput
* @returns {void}
*/
public error(input: LogItemMessage, ...extraInput: LogItemExtraInput): void {
this.processLogItem('ERROR', input, extraInput);
}
/**
* It evaluates whether the current Lambda function invocation has a cold start or not.
*
* @static
* @returns {void}
*/
public static evaluateColdStartOnce(): void {
if (!Logger.getColdStartEvaluatedValue()) {
Logger.evaluateColdStart();
}
}
/**
* It returns a boolean value which is true if the current Lambda function cold start has been already evaluated, false if not.
*
* @static
* @returns {boolean}
*/
public static getColdStartEvaluatedValue(): boolean {
return Logger.coldStartEvaluated;
}
/**
* It returns an optional boolean value, true if the current Lambda function invocation has a cold start, false otherwise.
*
* @static
* @returns {boolean | undefined}
*/
public static getColdStartValue(): boolean | undefined {
return Logger.coldStart;
}
/**
* It returns a boolean value, if true all the logs will be printed.
*
* @returns {boolean}
*/
public getLogsSampled(): boolean {
return this.logsSampled;
}
/**
* It prints a log item with level INFO.
*
* @param {LogItemMessage} input
* @param {Error | LogAttributes | unknown} extraInput
* @returns {void}
*/
public info(input: LogItemMessage, ...extraInput: LogItemExtraInput): void {
this.processLogItem('INFO', input, extraInput);
}
/**
* Method decorator that adds the current Lambda function context as extra
* information in all log items.
* The decorator can be used only when attached to a Lambda function handler which
* is written as method of a class, and should be declared just before the handler declaration.
*
* @see https://www.typescriptlang.org/docs/handbook/decorators.html#method-decorators
* @returns {HandlerMethodDecorator}
*/
public injectLambdaContext(): HandlerMethodDecorator {
return (target, propertyKey, descriptor) => {
const originalMethod = descriptor.value;
descriptor.value = (event, context, callback) => {
this.addContext(context);
return originalMethod?.apply(this, [ event, context, callback ]);
};
};
}
/**
* If the sample rate feature is enabled, the calculation that determines whether the logs
* will actually be printed or not for this invocation is done when the Logger class is
* initialized.
* This method will repeat that calculation (with possible different outcome).
*
* @returns {void}
*/
public refreshSampleRateCalculation(): void {
this.setLogsSampled();
}
/**
* It sets the value of a flag static propriety that tracks whether
* the cold start evaluation already took place.
*
* @param {boolean} value
* @static
* @returns {void}
*/
public static setColdStartEvaluatedValue(value: boolean): void {
Logger.coldStartEvaluated = value;
}
/**
* It sets the value of a flag static propriety that tracks whether
* the current Lambda invocation experienced a cold start.
*
* @static
* @param {boolean | undefined} value
* @returns {void}
*/
public static setColdStartValue(value: boolean | undefined): void {
Logger.coldStart = value;
}
/**
* It sets the user-provided sample rate value.
*
* @param {number} [sampleRateValue]
* @returns {void}
*/
public setSampleRateValue(sampleRateValue?: number): void {
this.powertoolLogData.sampleRateValue =
sampleRateValue ||
this.getCustomConfigService()?.getSampleRateValue() ||
this.getEnvVarsService().getSampleRateValue();
}
/**
* It prints a log item with level WARN.
*
* @param {LogItemMessage} input
* @param {Error | LogAttributes | unknown} extraInput
* @returns {void}
*/
public warn(input: LogItemMessage, ...extraInput: LogItemExtraInput): void {
this.processLogItem('WARN', input, extraInput);
}
/**
* It stored information that is printed in all log items.
*
* @param {Partial<PowertoolLogData>} attributesArray
* @private
* @returns {void}
*/
private addToPowertoolLogData(...attributesArray: Array<Partial<PowertoolLogData>>): void {
attributesArray.forEach((attributes: Partial<PowertoolLogData>) => {
this.powertoolLogData = merge(attributes, this.getPowertoolLogData());
});
}
/**
* It processes a particular log item so that it can be printed to stdout:
* - Merges ephemeral log attributes with persistent log attributes (printed for all logs) and additional info;
* - Formats all the log attributes;
*
* @private
* @param {LogLevel} logLevel
* @param {LogItemMessage} input
* @param {LogItemExtraInput} extraInput
* @returns {LogItem}
*/
private createAndPopulateLogItem(logLevel: LogLevel, input: LogItemMessage, extraInput: LogItemExtraInput): LogItem {
// TODO: this method's logic is hard to understand, there is an opportunity here to simplify this logic.
const unformattedBaseAttributes = merge({
logLevel,
timestamp: new Date(),
message: typeof input === 'string' ? input : input.message,
}, this.getPowertoolLogData());
const logItem = new LogItem({
baseAttributes: this.getLogFormatter().formatAttributes(unformattedBaseAttributes),
persistentAttributes: this.getPersistentLogAttributes(),
});
// Add ephemeral attributes
if (typeof input !== 'string') {
logItem.addAttributes(input);
}
extraInput.forEach((item: Error | LogAttributes | unknown) => {
const attributes = item instanceof Error ? { error: item } : item;
logItem.addAttributes(<LogAttributes>attributes);
});
return logItem;
}
/**
* It evaluates whether the current Lambda invocation experienced a
* cold start.
*
* @private
* @static
* @returns {void}
*/
private static evaluateColdStart(): void {
const coldStartValue = Logger.getColdStartValue();
if (typeof coldStartValue === 'undefined') {
Logger.setColdStartValue(true);
} else if (coldStartValue) {
Logger.setColdStartValue(false);
} else {
Logger.setColdStartValue(false);
}
Logger.setColdStartEvaluatedValue(true);
}
/**
* It returns the custom config service, an abstraction used to fetch environment variables.
*
* @private
* @returns {ConfigServiceInterface | undefined}
*/
private getCustomConfigService(): ConfigServiceInterface | undefined {
return this.customConfigService;
}
/**
* It returns the instance of a service that fetches environment variables.
*
* @private
* @returns {EnvironmentVariablesService}
*/
private getEnvVarsService(): EnvironmentVariablesService {
return <EnvironmentVariablesService> this.envVarsService;
}
/**
* It returns the instance of a service that formats the structure of a
* log item's keys and values in the desired way.
*
* @private
* @returns {LogFormatterInterface}
*/
private getLogFormatter(): LogFormatterInterface {
return <LogFormatterInterface> this.logFormatter;
}
/**
* It returns the log level set for the Logger instance.
*
* @private
* @returns {LogLevel}
*/
private getLogLevel(): LogLevel {
return <LogLevel> this.logLevel;
}
/**
* It returns the persistent log attributes, which are the attributes
* that will be logged in all log items.
*
* @private
* @returns {LogAttributes}
*/
private getPersistentLogAttributes(): LogAttributes {
return <LogAttributes> this.persistentLogAttributes;
}
/**
* It returns information that will be added in all log item by
* this Logger instance (different from user-provided persistent attributes).
*
* @private
* @returns {LogAttributes}
*/
private getPowertoolLogData(): PowertoolLogData {
return this.powertoolLogData;
}
/**
* It returns the numeric sample rate value.
*
* @private
* @returns {number}
*/
private getSampleRateValue(): number {
if (!this.powertoolLogData?.sampleRateValue) {
this.setSampleRateValue();
}
return <number> this.powertoolLogData?.sampleRateValue;
}
/**
* It returns true if the provided log level is valid.
*
* @param {LogLevel} logLevel
* @private
* @returns {boolean}
*/
private isValidLogLevel(logLevel?: LogLevel): boolean {
return typeof logLevel === 'string' && logLevel.toUpperCase() in this.logLevelThresholds;
}
/**
* It prints a given log with given log level.
*
* @param {LogLevel} logLevel
* @param {LogItem} log
* @private
*/
private printLog(logLevel: LogLevel, log: LogItem): void {
log.prepareForPrint();
const consoleMethod = logLevel.toLowerCase() as keyof ClassThatLogs;
console[consoleMethod](JSON.stringify(log.getAttributes(), this.removeCircularDependencies()));
}
/**
* It prints a given log with given log level.
*
* @param {LogLevel} logLevel
* @param {LogItem} log
* @private
*/
private processLogItem(logLevel: LogLevel, input: LogItemMessage, extraInput: LogItemExtraInput): void {
if (!this.shouldPrint(logLevel)) {
return;
}
this.printLog(logLevel, this.createAndPopulateLogItem(logLevel, input, extraInput));
}
/**
* When the data added in the log item contains object references,
* JSON.stringify() doesn't try to solve them and instead throws an error: TypeError: cyclic object value.
* To mitigate this issue, this method will find and remove all cyclic references.
*
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value
* @private
*/
private removeCircularDependencies(): (key: string, value: LogAttributes) => void {
const references = new WeakSet();
return (key, value) => {
let item = value;
if (item instanceof Error) {
item = this.getLogFormatter().formatError(item);
}
if (typeof item === 'object' && value !== null) {
if (references.has(item)) {
return;
}
references.add(item);
}
return item;
};
}
/**
* Sets the Logger's customer config service instance, which will be used
* to fetch environment variables.
*
* @private
* @param {ConfigServiceInterface} customConfigService
* @returns {void}
*/
private setCustomConfigService(customConfigService?: ConfigServiceInterface): void {
this.customConfigService = customConfigService ? customConfigService : undefined;
}
/**
* Sets the Logger's custom config service instance, which will be used
* to fetch environment variables.
*
* @private
* @param {ConfigServiceInterface} customConfigService
* @returns {void}
*/
private setEnvVarsService(): void {
this.envVarsService = new EnvironmentVariablesService();
}
/**
* It sets the log formatter instance, in charge of giving a custom format
* to the structured logs
*
* @private
* @param {LogFormatterInterface} logFormatter
* @returns {void}
*/
private setLogFormatter(logFormatter?: LogFormatterInterface): void {
this.logFormatter = logFormatter || new PowertoolLogFormatter();
}
/**
* It sets the Logger's instance log level.
*
* @private
* @param {LogLevel} logLevel
* @returns {void}
*/
private setLogLevel(logLevel?: LogLevel): void {
if (this.isValidLogLevel(logLevel)) {
this.logLevel = (<LogLevel>logLevel).toUpperCase();
return;
}
const customConfigValue = this.getCustomConfigService()?.getLogLevel();
if (this.isValidLogLevel(customConfigValue)) {
this.logLevel = (<LogLevel>customConfigValue).toUpperCase();
return;
}
const envVarsValue = this.getEnvVarsService().getLogLevel();
if (this.isValidLogLevel(envVarsValue)) {
this.logLevel = (<LogLevel>envVarsValue).toUpperCase();
return;
}
this.logLevel = Logger.defaultLogLevel;
}
/**
* If the sample rate feature is enabled, it sets a propriety that tracks whether this Lambda function invocation
* will print logs or not.
*
* @private
* @returns {void}
*/
private setLogsSampled(): void {
const sampleRateValue = this.getSampleRateValue();
// TODO: revisit Math.random() as it's not a real randomization
this.logsSampled = sampleRateValue !== undefined && (sampleRateValue === 1 || Math.random() < sampleRateValue);
}
/**
* It configures the Logger instance settings that will affect the Logger's behaviour
* and the content of all logs.
*
* @private
* @param {LoggerOptions} options
* @returns {Logger}
*/
private setOptions(options: LoggerOptions): Logger {
const {
logLevel,
serviceName,
sampleRateValue,
logFormatter,
customConfigService,
persistentLogAttributes,
environment,
} = options;
this.setEnvVarsService();
this.setCustomConfigService(customConfigService);
this.setLogLevel(logLevel);
this.setSampleRateValue(sampleRateValue);
this.setLogsSampled();
this.setLogFormatter(logFormatter);
this.setPowertoolLogData(serviceName, environment);
this.addPersistentLogAttributes(persistentLogAttributes);
return this;
}
/**
* It adds important data to the Logger instance that will affect the content of all logs.
*
* @param {string} serviceName
* @param {Environment} environment
* @param {LogAttributes} persistentLogAttributes
* @private
* @returns {void}
*/
private setPowertoolLogData(
serviceName?: string,
environment?: Environment,
persistentLogAttributes: LogAttributes = {},
): void {
this.addToPowertoolLogData(
{
awsRegion: this.getEnvVarsService().getAwsRegion(),
environment:
environment ||
this.getCustomConfigService()?.getCurrentEnvironment() ||
this.getEnvVarsService().getCurrentEnvironment(),
sampleRateValue: this.getSampleRateValue(),
serviceName:
serviceName || this.getCustomConfigService()?.getServiceName() || this.getEnvVarsService().getServiceName() || Logger.defaultServiceName,
xRayTraceId: this.getEnvVarsService().getXrayTraceId(),
},
persistentLogAttributes,
);
}
/**
* It checks whether the current log item should/can be printed.
*
* @param {string} serviceName
* @param {Environment} environment
* @param {LogAttributes} persistentLogAttributes
* @private
* @returns {boolean}
*/
private shouldPrint(logLevel: LogLevel): boolean {
if (this.logLevelThresholds[logLevel] >= this.logLevelThresholds[this.getLogLevel()]) {
return true;
}
return this.getLogsSampled();
}
}
export { Logger };