
Debug Your First AWS Lambda Function with Amazon CloudWatch Logs
Learn how to add useful logs to a Python Lambda function, find them in Amazon CloudWatch, and investigate failed requests. Build a simple task-validation example while exploring structured logging and safe debugging practices.
Introduction
Deploying a function is only the beginning. When an application behaves unexpectedly, you need a way to understand what happened inside it.
Consider a task-management application: a user submits a task, but the request fails. Did the application receive an empty title? Did validation succeed? Did the function encounter an unexpected error?
AWS Lambda can send function logs to Amazon CloudWatch Logs when its execution role has the necessary permissions. These logs provide a record you can inspect while investigating application behavior. docs.aws.amazon
This article demonstrates a small Python example and a practical debugging workflow.
1. Understand the Logging Flow
For this project, the flow is:
textTest event or application request | v Python Lambda function | | Application log messages v Amazon CloudWatch Logs | v Inspect and investigateLambda captures supported logging output and sends it to the configured CloudWatch Logs destination. The function’s execution role must have the required logging permissions; writing a log statement alone does not establish those permissions.docs.aws.amazon+1
2. Start with a Small Function
Our example validates a task title. It does not save tasks or connect to a database, so there are fewer moving parts to investigate.
pythonimport logging
logger = logging.getLogger()logger.setLevel(logging.INFO)
def lambda_handler(event, context): logger.info("Task validation started")
if not isinstance(event, dict): logger.warning("Task rejected: invalid event format") return { "statusCode": 400, "body": "Expected a JSON object" }
title = event.get("title")
if not isinstance(title, str) or not title.strip(): logger.warning("Task rejected: missing or empty title") return { "statusCode": 400, "body": "A non-empty task title is required" }
logger.info("Task validation completed")
return { "statusCode": 200, "body": "Task is valid" }This handler expects a direct test event with a top-level
title field:json{ "title": "Complete cloud computing assignment"}It is not a complete API Gateway handler. An API integration may place the submitted JSON inside a
body field, requiring additional parsing.Python’s standard
logging library is supported by Lambda and can produce structured application logs when the function is configured to use JSON log format. aws.amazon 3. Use Log Levels Intentionally
The example uses two levels:
-
INFOrecords normal processing milestones.
-
WARNINGrecords a rejected input that the function handles deliberately.
For unexpected failures, an
ERROR log can help distinguish operational problems from ordinary validation outcomes. Lambda supports log-level controls for JSON-formatted logs, allowing you to choose the level of detail sent to CloudWatch. aws.amazon In this example, returning a
400 response is a handled validation result. It is not the same as raising an exception and failing the Lambda invocation.4. Enable Structured JSON Logs
For a supported Python runtime, choose JSON as the function’s log format. Lambda then captures standard Python logging output as structured JSON with fields including:
-
timestamp
-
level
-
message
-
requestId
A simplified illustrative entry would look like this:
json{ "timestamp": "2026-11-11T15:00:00Z", "level": "WARNING", "message": "Task rejected: missing or empty title", "requestId": "example-request-id"}Structured fields make logs easier to search and analyze than a collection of unrelated text messages. CloudWatch Logs Insights can discover fields in JSON logs and use them in queries. aws.amazon
5. Test Successful and Rejected Inputs
Run the function with several direct test events:
Test event | Expected result |
|---|---|
{"title": "Study AWS"} | Validation succeeds |
{"title": ""} | Empty title is rejected |
{"title": " "} | Whitespace-only title is rejected |
{} | Missing title is rejected |
{"title": 123} | Non-string title is rejected |
Then inspect the function’s CloudWatch logs. Compare the returned result with the messages recorded for each invocation. Lambda’s logging tools let you inspect invocation logs and query them using CloudWatch Logs Insights. aws.amazon
The purpose is not simply to confirm that logs exist. It is to check whether they explain why the function took a particular path.
6. Search for Validation Warnings
With JSON logging enabled and the relevant log group selected, this CloudWatch Logs Insights query can help find recent warning entries:
sqlfields @timestamp, level, message, requestId| filter level = "WARNING"| sort @timestamp desc| limit 20The query uses the fields emitted by Python’s JSON logging configuration. CloudWatch Logs Insights supports querying automatically discovered JSON fields.aws.amazon+1
If the function uses plain-text logs or a custom logging format, the available fields may differ.
7. Log Decisions, Not Entire Requests
For this project, the logs describe what the application decided:
textTask validation startedTask rejected: missing or empty titleTask validation completedThey do not include the submitted task title or the complete incoming event.
That is a useful safety habit: avoid logging passwords, access tokens, credentials, or private user content. AWS’s Powertools logging documentation disables incoming-event logging by default to help prevent sensitive information from being recorded. aws.amazon
When more context is necessary, choose specific fields intentionally instead of automatically dumping the entire request.
8. Follow a Repeatable Debugging Workflow
For this example, use the following process:
- Reproduce the issue with a small test event.
- Check the function’s returned result.
- Find the matching invocation logs.
- Follow the messages to identify the last completed step.
- Change one relevant part of the code.
- Run the same test again.
- Repeat the successful-input tests to check for regressions.
If no logs appear, verify the configured log destination and the function’s execution-role permissions before assuming the handler did not run. Lambda requires appropriate permissions to write to CloudWatch Logs.docs.aws.amazon+1
Conclusion
Useful logging makes a small cloud application easier to understand. With Lambda and CloudWatch Logs, you can record processing milestones, identify rejected inputs, and investigate individual invocations through structured fields.aws.amazon+1
Start with a few meaningful messages rather than logging everything. The goal is to explain the application’s behavior clearly without exposing unnecessary data.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article