-
Notifications
You must be signed in to change notification settings - Fork 154
/
Copy pathLogger.ts
316 lines (248 loc) · 9.08 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
import { Context } from 'aws-lambda';
import { LogItem } from './log';
import { cloneDeep, merge } from 'lodash/fp';
import { ConfigServiceInterface, EnvironmentVariablesService } from './config';
import {
Environment,
HandlerMethodDecorator,
LambdaFunctionContext,
LogAttributes,
ClassThatLogs,
LoggerOptions,
LogItemExtraInput,
LogItemMessage,
LogLevel,
LogLevelThresholds,
PowertoolLogData,
} from '../types';
import { LogFormatterInterface, PowertoolLogFormatter } from './formatter';
class Logger implements ClassThatLogs {
public static coldStart: boolean = true;
private customConfigService?: ConfigServiceInterface;
private static readonly defaultLogLevel: LogLevel = 'INFO';
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>{};
public constructor(options: LoggerOptions = {}) {
this.setOptions(options);
}
public addContext(context: Context): void {
const lambdaContext: Partial<LambdaFunctionContext> = {
invokedFunctionArn: context.invokedFunctionArn,
coldStart: Logger.isColdStart(),
awsRequestId: context.awsRequestId,
memoryLimitInMB: Number(context.memoryLimitInMB),
functionName: context.functionName,
functionVersion: context.functionVersion,
};
this.addToPowertoolLogData({
lambdaContext
});
}
public addPersistentLogAttributes(attributes?: LogAttributes): void {
this.persistentLogAttributes = merge(this.getPersistentLogAttributes(), attributes);
}
public appendKeys(attributes?: LogAttributes): void {
this.addPersistentLogAttributes(attributes);
}
public createChild(options: LoggerOptions = {}): Logger {
return cloneDeep(this).setOptions(options);
}
public debug(input: LogItemMessage, ...extraInput: LogItemExtraInput): void {
if (!this.shouldPrint('DEBUG')) {
return;
}
this.printLog(this.createAndPopulateLogItem('DEBUG', input, extraInput));
}
public error(input: LogItemMessage, ...extraInput: LogItemExtraInput): void {
this.printLog(this.createAndPopulateLogItem('ERROR', input, extraInput));
}
public getLogsSampled(): boolean {
return this.logsSampled;
}
public info(input: LogItemMessage, ...extraInput: LogItemExtraInput): void {
if (!this.shouldPrint('INFO')) {
return;
}
this.printLog(this.createAndPopulateLogItem('INFO', input, extraInput));
}
public injectLambdaContext(): HandlerMethodDecorator {
return (target, propertyKey, descriptor) => {
const originalMethod = descriptor.value;
descriptor.value = (event, context, callback) => {
this.addContext(context);
const result = originalMethod?.apply(this, [ event, context, callback ]);
return result;
};
};
}
public static isColdStart(): boolean {
if (Logger.coldStart === true) {
Logger.coldStart = false;
return true;
}
return false;
}
public refreshSampleRateCalculation(): void {
this.setLogsSampled();
}
public setSampleRateValue(sampleRateValue?: number): void {
this.powertoolLogData.sampleRateValue = sampleRateValue || this.getCustomConfigService()?.getSampleRateValue()
|| this.getEnvVarsService().getSampleRateValue();
}
public warn(input: LogItemMessage, ...extraInput: LogItemExtraInput): void {
if (!this.shouldPrint('WARN')) {
return;
}
this.printLog(this.createAndPopulateLogItem('WARN', input, extraInput));
}
private addToPowertoolLogData(...attributesArray: Array<Partial<PowertoolLogData>>): void {
attributesArray.forEach((attributes: Partial<PowertoolLogData>) => {
this.powertoolLogData = merge(this.getPowertoolLogData(), attributes);
});
}
private createAndPopulateLogItem(logLevel: LogLevel, input: LogItemMessage, extraInput: LogItemExtraInput): LogItem {
const unformattedBaseAttributes = merge(
this.getPowertoolLogData(),
{
logLevel,
timestamp: new Date(),
message: (typeof input === 'string') ? input : input.message
});
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) => {
const attributes = (item instanceof Error) ? { error: item } : item;
logItem.addAttributes(attributes);
});
return logItem;
}
private getCustomConfigService(): ConfigServiceInterface | undefined {
return this.customConfigService;
}
private getEnvVarsService(): EnvironmentVariablesService {
return <EnvironmentVariablesService> this.envVarsService;
}
private getLogFormatter(): LogFormatterInterface {
return <LogFormatterInterface> this.logFormatter;
}
private getLogLevel(): LogLevel {
return <LogLevel> this.logLevel;
}
private getPersistentLogAttributes(): LogAttributes {
return <LogAttributes> this.persistentLogAttributes;
}
private getPowertoolLogData(): PowertoolLogData {
return this.powertoolLogData;
}
private getSampleRateValue(): number {
if (!this.powertoolLogData?.sampleRateValue) {
this.setSampleRateValue();
}
return <number> this.powertoolLogData?.sampleRateValue;
}
private isValidLogLevel(logLevel?: LogLevel): boolean {
return typeof logLevel === 'string' && logLevel.toUpperCase() in this.logLevelThresholds;
}
private printLog(log: LogItem): void {
log.prepareForPrint();
const references = new WeakSet();
console.log(JSON.parse(JSON.stringify(log.getAttributes(), (key: string, value: LogAttributes) => {
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;
})));
}
private setCustomConfigService(customConfigService?: ConfigServiceInterface): void {
this.customConfigService = customConfigService ? customConfigService : undefined;
}
private setEnvVarsService(): void {
this.envVarsService = new EnvironmentVariablesService();
}
private setLogFormatter(logFormatter?: LogFormatterInterface): void {
this.logFormatter = logFormatter || new PowertoolLogFormatter();
}
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;
}
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);
}
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;
}
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(),
xRayTraceId: this.getEnvVarsService().getXrayTraceId(),
}, persistentLogAttributes);
}
private shouldPrint(logLevel: LogLevel): boolean {
if (this.logLevelThresholds[logLevel] >= this.logLevelThresholds[this.getLogLevel()]) {
return true;
}
return this.getLogsSampled();
}
}
export {
Logger
};