Best practices for your debugging environment - AWS Lambda

Best practices for your debugging environment

Testing in a deployed Lambda function

In the Lambda console, the Test option enables you to configure a test event for the handler code. Providing the same event that is logged to CloudWatch allows you to replay an event when testing. In the Configure test event dialog box, paste the event and choose Create.


               debugging ops figure 14

Testing locally

Lambda functions always receive a JSON event payload in the first parameter of the function handler. You can log out this event in the first line of any Lambda function, by adding a logging line like:

    console.log(JSON.stringify(event, null, 2))

After invocation, in CloudWatch Logs this appears in the log stream of the function, and you can copy this event information from the stream:


               debugging ops figure 14

To test the same event locally on a development machine, create a test harness that loads the event, sets any environment variables, and triggers the handler code. For example, in Node.js:

// Mock event const event = require('./localTestEvent') // Mock environment variables process.env.AWS_REGION = 'us-east-1' process.env.localTest = true process.env.OutputBucket = 'your-bucket-name' // Lambda handler const { handler } = require('./app') const main = async () => { console.time('localTest') await handler(event) console.timeEnd('localTest') } main().catch(error => console.error(error))

This allows you to set breakpoints in your IDE, interact with cloud-based resources, and debug the identical event that resulted in a production error. This approach enables fast local iteration when developing new code, and can be used with unit testing frameworks as part of build processes.


               debugging ops figure 16

Alternatively, if you are using Serverless Framework or AWS SAM, these both have options for local testing. For example, the command sam local starts a local Docker container to invoke the function and you can generate sample event payload. This allows you to quickly test code without needing to redeploy. Serverless Offline provides similar functionality for Serverless Framework.

Replaying large numbers of events with Amazon EventBridge

Some microservices process large numbers of events and maintain state in another service like DynamoDB. For these services, either when debugging production issues or testing new features, it can be useful to replay all the messages for a given time period to help identify issues.

For events sourced from an EventBridge event bus, you can enable event archiving on the bus. The archive can capture some or all events depending upon the content filter applied, and you can define a duration. The EventBridge console enables you to configure a replay of an archive.

For more information about using this feature, see this blog post or the documentation.