Skip to content

Commit 03cd539

Browse files
committed
chore(logger): removed unused var
1 parent 1bd7808 commit 03cd539

File tree

4 files changed

+141
-30
lines changed

4 files changed

+141
-30
lines changed

Diff for: packages/logger/src/Logger.ts

+28-17
Original file line numberDiff line numberDiff line change
@@ -275,8 +275,6 @@ class Logger extends Utility implements ClassThatLogs {
275275
* @returns {HandlerMethodDecorator}
276276
*/
277277
public injectLambdaContext(options?: HandlerOptions): HandlerMethodDecorator {
278-
const isClearStateEnabled = options && options.clearState === true;
279-
280278
return (target, _propertyKey, descriptor) => {
281279
/**
282280
* The descriptor.value is the method this decorator decorates, it cannot be undefined.
@@ -286,30 +284,43 @@ class Logger extends Utility implements ClassThatLogs {
286284

287285
descriptor.value = (event, context, callback) => {
288286

289-
let initialPersistentAttributes: LogAttributes = {};
290-
if (isClearStateEnabled) {
291-
initialPersistentAttributes = { ...this.getPersistentLogAttributes() };
292-
}
293-
294-
this.addContext(context);
295-
let shouldLogEvent = undefined;
296-
if ( options && options.hasOwnProperty('logEvent') ) {
297-
shouldLogEvent = options.logEvent;
298-
}
299-
this.logEventIfEnabled(event, shouldLogEvent);
287+
const initialPersistentAttributes = Logger.injectLambdaContextBefore(this, event, context, options);
300288

301289
/* eslint-disable @typescript-eslint/no-non-null-assertion */
302-
const result = originalMethod!.apply(target, [ event, context, callback ]);
303-
304-
if (isClearStateEnabled) {
305-
this.setPersistentLogAttributes(initialPersistentAttributes);
290+
let result: unknown;
291+
try {
292+
result = originalMethod!.apply(target, [ event, context, callback ]);
293+
} catch (error) {
294+
throw error;
295+
} finally {
296+
Logger.injectLambdaContextAfterOrOnError(this, initialPersistentAttributes, options);
306297
}
307298

308299
return result;
309300
};
310301
};
311302
}
312303

304+
public static injectLambdaContextAfterOrOnError(logger: Logger, initialPersistentAttributes: LogAttributes = {}, options?: HandlerOptions): void {
305+
if (options && options.clearState === true) {
306+
logger.setPersistentLogAttributes(initialPersistentAttributes);
307+
}
308+
}
309+
310+
public static injectLambdaContextBefore(logger: Logger, event: unknown, context: Context, options?: HandlerOptions): LogAttributes | undefined {
311+
logger.addContext(context);
312+
313+
let shouldLogEvent = undefined;
314+
if (options && options.hasOwnProperty('logEvent')) {
315+
shouldLogEvent = options.logEvent;
316+
}
317+
logger.logEventIfEnabled(event, shouldLogEvent);
318+
319+
if (options && options.clearState === true) {
320+
return { ...logger.getPersistentLogAttributes() };
321+
}
322+
}
323+
313324
/**
314325
* Logs a Lambda invocation event, if it *should*.
315326
*

Diff for: packages/logger/src/middleware/middy.ts

+8-13
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import type { Logger } from '../Logger';
1+
import { Logger } from '../Logger';
22
import type middy from '@middy/core';
33
import { HandlerOptions, LogAttributes } from '../types';
44

@@ -30,34 +30,29 @@ import { HandlerOptions, LogAttributes } from '../types';
3030
const injectLambdaContext = (target: Logger | Logger[], options?: HandlerOptions): middy.MiddlewareObj => {
3131

3232
const loggers = target instanceof Array ? target : [target];
33-
const persistentAttributes: LogAttributes[] = [];
33+
const persistentAttributes: (LogAttributes | undefined)[] = [];
3434

3535
const injectLambdaContextBefore = async (request: middy.Request): Promise<void> => {
3636
loggers.forEach((logger: Logger) => {
37-
logger.addContext(request.context);
37+
const initialPersistentAttributes = Logger.injectLambdaContextBefore(logger, request.event, request.context, options);
3838
if (options && options.clearState === true) {
39-
persistentAttributes.push({ ...logger.getPersistentLogAttributes() });
39+
persistentAttributes.push(initialPersistentAttributes);
4040
}
41-
42-
let shouldLogEvent = undefined;
43-
if ( options && options.hasOwnProperty('logEvent') ) {
44-
shouldLogEvent = options.logEvent;
45-
}
46-
logger.logEventIfEnabled(request.event, shouldLogEvent);
4741
});
4842
};
4943

50-
const injectLambdaContextAfter = async (): Promise<void> => {
44+
const injectLambdaContextAfterOrOnError = async (): Promise<void> => {
5145
if (options && options.clearState === true) {
5246
loggers.forEach((logger: Logger, index: number) => {
53-
logger.setPersistentLogAttributes(persistentAttributes[index]);
47+
Logger.injectLambdaContextAfterOrOnError(logger, persistentAttributes[index], options);
5448
});
5549
}
5650
};
5751

5852
return {
5953
before: injectLambdaContextBefore,
60-
after: injectLambdaContextAfter
54+
after: injectLambdaContextAfterOrOnError,
55+
onError: injectLambdaContextAfterOrOnError
6156
};
6257
};
6358

Diff for: packages/logger/tests/unit/Logger.test.ts

+49
Original file line numberDiff line numberDiff line change
@@ -982,6 +982,55 @@ describe('Class: Logger', () => {
982982

983983
});
984984

985+
test('when used as decorator with the clear state flag enabled and the handler throws, the persistent log attributes added in the handler are removed after the handler\'s code is executed', async () => {
986+
987+
// Prepare
988+
const logger = new Logger({
989+
logLevel: 'DEBUG',
990+
persistentLogAttributes: {
991+
foo: 'bar',
992+
biz: 'baz'
993+
}
994+
});
995+
996+
type CustomEvent = { user_id: string };
997+
998+
class LambdaFunction implements LambdaInterface {
999+
1000+
@logger.injectLambdaContext({ clearState: true })
1001+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
1002+
// @ts-ignore
1003+
public handler<TResult>(event: CustomEvent, _context: Context, _callback: Callback<TResult>): void | Promise<TResult> {
1004+
// Only add these persistent for the scope of this lambda handler
1005+
logger.appendKeys({
1006+
details: { user_id: event['user_id'] }
1007+
});
1008+
logger.debug('This is a DEBUG log with the user_id');
1009+
logger.debug('This is another DEBUG log with the user_id');
1010+
1011+
throw new Error('Unexpected error occurred!');
1012+
}
1013+
}
1014+
1015+
const persistentAttribs = { ...logger.getPersistentLogAttributes() };
1016+
1017+
// Act
1018+
try {
1019+
await new LambdaFunction().handler({ user_id: '123456' }, dummyContext, () => console.log('Lambda invoked!'));
1020+
} catch (error) {
1021+
// Do nothing
1022+
}
1023+
const persistentAttribsAfterInvocation = { ...logger.getPersistentLogAttributes() };
1024+
1025+
// Assess
1026+
expect(persistentAttribs).toEqual({
1027+
foo: 'bar',
1028+
biz: 'baz'
1029+
});
1030+
expect(persistentAttribsAfterInvocation).toEqual(persistentAttribs);
1031+
1032+
});
1033+
9851034
test('when used as decorator with the log event flag enabled, it logs the event', async () => {
9861035

9871036
// Prepare

Diff for: packages/logger/tests/unit/middleware/middy.test.ts

+56
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,62 @@ describe('Middy middleware', () => {
207207

208208
});
209209

210+
test('when enabled and the handler throws, the persistent log attributes added within the handler scope are removed after the invocation ends', async () => {
211+
212+
// Prepare
213+
const logger = new Logger({
214+
logLevel: 'DEBUG',
215+
persistentLogAttributes: {
216+
foo: 'bar',
217+
biz: 'baz'
218+
}
219+
});
220+
const context = {
221+
callbackWaitsForEmptyEventLoop: true,
222+
functionVersion: '$LATEST',
223+
functionName: 'foo-bar-function',
224+
memoryLimitInMB: '128',
225+
logGroupName: '/aws/lambda/foo-bar-function',
226+
logStreamName: '2021/03/09/[$LATEST]abcdef123456abcdef123456abcdef123456',
227+
invokedFunctionArn: 'arn:aws:lambda:eu-west-1:123456789012:function:foo-bar-function',
228+
awsRequestId: 'abcdef123456abcdef123456',
229+
getRemainingTimeInMillis: () => 1234,
230+
done: () => console.log('Done!'),
231+
fail: () => console.log('Failed!'),
232+
succeed: () => console.log('Succeeded!'),
233+
};
234+
235+
const lambdaHandler = (event: { user_id: string }): void => {
236+
// Only add these persistent for the scope of this lambda handler
237+
logger.appendKeys({
238+
details: { user_id: event['user_id'] }
239+
});
240+
logger.debug('This is a DEBUG log with the user_id');
241+
logger.debug('This is another DEBUG log with the user_id');
242+
243+
throw new Error('Unexpected error occurred!');
244+
};
245+
246+
const handler = middy(lambdaHandler).use(injectLambdaContext(logger, { clearState: true }));
247+
const persistentAttribs = { ...logger.getPersistentLogAttributes() };
248+
249+
// Act
250+
try {
251+
await handler({ user_id: '123456' }, context, () => console.log('Lambda invoked!'));
252+
} catch (error) {
253+
// Do nothing
254+
}
255+
const persistentAttribsAfterInvocation = { ...logger.getPersistentLogAttributes() };
256+
257+
// Assess
258+
expect(persistentAttribs).toEqual({
259+
foo: 'bar',
260+
biz: 'baz'
261+
});
262+
expect(persistentAttribsAfterInvocation).toEqual(persistentAttribs);
263+
264+
});
265+
210266
});
211267

212268
describe('Feature: log event', () => {

0 commit comments

Comments
 (0)