Skip to content

Bug: clearState not working when lambda throws error #1027

Closed
@Crafoord

Description

@Crafoord

Bug description

When using addPersistentLogAttributes :

logger.addPersistentLogAttributes({ memberId: 'test'  });

and using the middy to clearState:

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

and then exiting the lambda by throwing an error, the next invocation will still have the persistentLogAttributes present. My guess is that the middleware never runs because of the error.

Expected Behavior

When lambda crashes the middleware should still clearState.

Current Behavior

When lambda crashes the middleware does not clearState.

Possible Solution

I guess there could be a way of handling this by not using middleware but there is no documentation of how to clearState without it.

Steps to Reproduce

  1. create handler like:
import { Handler } from 'aws-lambda';
import middy from '@middy/core';
import { injectLambdaContext, Logger } from '@aws-lambda-powertools/logger';

const logger = new Logger();

const lambdaHandler: Handler = async (event) => {
  logger.info('Before adding memberId');
  logger.addPersistentLogAttributes({ memberId: 'test'  });
  logger.info('After adding memberId');

  throw new Error();
};

export const handler = middy(lambdaHandler).use(
  injectLambdaContext(logger, { clearState: true })
);
  1. invoce lambda
  2. check logs, Before adding memberId will not have memberId property, After adding memberId will have memberId: test
  3. invoce lambda again
  4. check logs Before adding memberId will have memberId: test (which is not supposed to be there).

Environment

"@aws-lambda-powertools/logger": "^1.0.2",
"@middy/core": "^3.1.0"

Lambda runtime: nodejs16.x

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