# Better Lambda logging with Python Powertools

When writing Lambdas in Python there are some things I usually have to do in order to get them working. It usually goes something like this:

1. Create python lambda
2. Dump the event so I can inspect it and see what I need
3. Make changes
5. Rinse and Repeat

So the initial Lambda looks something like this:

But lately, I’ve discovered some solutions to make this better.

## Generate test events

First off, rather than creating a Lambda, dumping the event to view it and continuing from there, use SAM CLI to create example events:

That outputs this:

This results in example events you can save for testing and customize as needed. Many events (but not all) are supported. Now you can use something like sam local invoke and point to that event for testing. Coupled with either moto or localstack you can use it for testing purposes locally.

## Better Lambda Logging

For a long time I’ve just used print() statements in Lambdas to get what I wanted out of them. This was a big mistake. First off, AWS extends the logging format used by the default Python logging library, so just by using that you get additional context of log level, and invocation in the log output. But there is even a better solution, Lambda Powertools Python.

By using this logging functionality you can get better structured logs in CloudWatch Logs and even automatically include the event. The example Lambda to invalidate a CloudFront cache below uses it to output the event to the logs, and also logs some additional info in a structured format.

Resulting in logs that look like this:

Now the resulting logs are much easier to review visually, easier to parse if needed and easier to query with CloudWatch Log Insights. All with just an additional dependency and adding a few lines of code to the Lambda.