-
Notifications
You must be signed in to change notification settings - Fork 153
/
Copy pathLogger.ts
653 lines (586 loc) · 18.9 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
import type { Context } from 'aws-lambda';
import { Utility } from '@aws-lambda-powertools/commons';
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';
/**
* ## 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
*
* ## Usage
*
* For more usage examples, see [our documentation](https://awslabs.github.io/aws-lambda-powertools-typescript/latest/core/logger/).
*
* ### Basic usage
*
* @example
* ```typescript
* import { Logger } from "@aws-lambda-powertools/logger";
*
* // Logger parameters fetched from the environment variables:
* const logger = new Logger();
* ```
*
* ### Functions usage with manual instrumentation
*
* If you prefer to manually instrument your Lambda handler you can use the methods in the Logger class directly.
*
* @example
* ```typescript
* import { Logger } from "@aws-lambda-powertools/logger";
*
* const logger = new Logger();
*
* export const handler = async (_event, context) => {
* logger.addContext(context);
* logger.info("This is an INFO log with some context");
* };
* ```
*
* ### Functions usage with middleware
*
* If you use function-based Lambda handlers you can use the [injectLambdaContext()](#injectLambdaContext)
* middy middleware to automatically add context to your Lambda logs.
*
* @example
* ```typescript
* import { Logger, injectLambdaContext } from "@aws-lambda-powertools/logger";
* import middy from '@middy/core';
*
* const logger = new Logger();
*
* const lambdaHandler = async (_event: any, _context: any) => {
* logger.info("This is an INFO log with some context");
* };
*
* export const handler = middy(lambdaHandler).use(injectLambdaContext(logger));
* ```
*
* ### Object oriented usage with decorators
*
* If instead you use TypeScript classes to wrap your Lambda handler you can use the [@logger.injectLambdaContext()](./_aws_lambda_powertools_logger.Logger.html#injectLambdaContext) decorator.
*
* @example
* ```typescript
* import { Logger } from "@aws-lambda-powertools/logger";
* import { LambdaInterface } from '@aws-lambda-powertools/commons';
*
* const logger = new Logger();
*
* class Lambda implements LambdaInterface {
* // Decorate your handler class method
* @logger.injectLambdaContext()
* public async handler(_event: any, _context: any): Promise<void> {
* logger.info("This is an INFO log with some context");
* }
* }
*
* export const myFunction = new Lambda();
* export const handler = myFunction.handler;
* ```
*
* @class
* @implements {ClassThatLogs}
* @see https://awslabs.github.io/aws-lambda-powertools-typescript/latest/core/logger/
*/
class Logger extends Utility implements ClassThatLogs {
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 = {}) {
super();
this.setOptions(options);
}
/**
* It adds the current Lambda function's invocation context data to the powertoolLogData property of the instance.
* This context data will be part of all printed log items.
*
* @param {Context} context
* @returns {void}
*/
public addContext(context: Context): void {
const lambdaContext: Partial<LambdaFunctionContext> = {
invokedFunctionArn: context.invokedFunctionArn,
coldStart: this.getColdStart(),
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 {
merge(this.persistentLogAttributes, attributes);
}
/**
* 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 | string} 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 | string} extraInput
* @returns {void}
*/
public error(input: LogItemMessage, ...extraInput: LogItemExtraInput): void {
this.processLogItem('ERROR', input, extraInput);
}
/**
* 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 | string} 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(target, [ 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 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 | string} extraInput
* @returns {void}
*/
public warn(input: LogItemMessage, ...extraInput: LogItemExtraInput): void {
this.processLogItem('WARN', input, extraInput);
}
/**
* It stores 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>) => {
merge(this.powertoolLogData, attributes);
});
}
/**
* 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 | string) => {
const attributes: LogAttributes =
item instanceof Error ? { error: item } :
typeof item === 'string' ? { extra: item } :
item;
logItem.addAttributes(attributes);
});
return logItem;
}
/**
* 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 | Error) => 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 property 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 };