Skip to content

Bug: Log state not cleared before logging event in middleware #1328

Closed
@angelcabo

Description

@angelcabo

Expected Behaviour

I am currently using the injectLambdaContext middleware with the middy library to both clear persistent log state and log the invocation event. My lambda handler function puts a request ID on the logger for debugging purposes.

According to the docs, because I've set clearState to true, persistent attributes added inside the handler will NOT be cached. So, my expectation would be that the request_id attribute would never be shared between invocations (assuming each invocation contained a unique request_id).

Current Behaviour

I am seeing the initial event logged by the middleware including persistent attributes added from a previous invocation, despite clearState being set to true

Code snippet

const logger = new Logger({
    logLevel: 'DEBUG',
    persistentLogAttributes: {
        foo: 'bar'
    }
});

const lambdaHandler = async (event: { headers: {x-request-id: string } }, _context: unknown): Promise<void> => {
    logger.appendKeys({request_id: event.headers['x-request-id']});
    ...
};

export const handler = middy(lambdaHandler)
    .use(injectLambdaContext(logger, { logEvent: true, clearState: true }));

Possible Solution

It seems like the logEvent step occurs in the "before" middleware, here: https://github.com/awslabs/aws-lambda-powertools-typescript/blob/main/packages/logger/src/Logger.ts#L338 whereas the clearState step happens in the "after" middleware step here: https://github.com/awslabs/aws-lambda-powertools-typescript/blob/main/packages/logger/src/Logger.ts#L346, with the initialPersistentAttributes being used to override any existing persistent attributes set in a previous invocation.

Steps to Reproduce

  1. Host a lambda behind API Gateway.
  2. Invoke the lambda twice, each time using a unique x-request-id header in the request.
  3. Observe via CloudWatch logs that the "Lambda invocation event" log line for the second invocation (assuming the second invocation was warm) has the first x-request-id header value in the request_id logger attribute.

AWS Lambda Powertools for TypeScript version

latest

AWS Lambda function runtime

16.x

Packaging format used

Lambda Layers

Execution logs

No response

Metadata

Metadata

Assignees

Labels

bugSomething isn't workingcompletedThis item is complete and has been merged/shippedloggerThis item relates to the Logger Utility

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions