4.1.1 Debug Code to Identify Defects
Debug Code to Identify Defects
Lambda Debugging Approaches
| Approach | Tool | Mô tả |
|---|
| Local testing | SAM CLI | sam local invoke với test events |
| Console testing | AWS Console | Test events trực tiếp |
| Logging | CloudWatch Logs | Print/log statements |
| Tracing | X-Ray | End-to-end request tracing |
| Step-through | IDE debugger | Local debugging với SAM |
Common Code Defects
| Defect | Symptom | Debug Method |
|---|
| Unhandled exception | Lambda error, 502 | CloudWatch Logs → stack trace |
| Wrong response format | API GW 502 | Check statusCode, body format |
| Missing env variable | KeyError/undefined | Check Lambda configuration |
| Timeout | Task timed out | Check Duration in REPORT line |
| Memory exceeded | Runtime.ExitError | Check Max Memory Used |
Lambda REPORT Line
REPORT RequestId: abc-123
Duration: 250.00 ms
Billed Duration: 300 ms
Memory Size: 256 MB
Max Memory Used: 240 MB ← Close to limit!
Init Duration: 500.00 ms ← Cold start
Debugging Best Practices
import logging
import json
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def handler(event, context):
logger.info(f"Event: {json.dumps(event)}")
logger.info(f"Remaining time: {context.get_remaining_time_in_millis()}ms")
try:
result = process(event)
logger.info(f"Success: {result}")
return {'statusCode': 200, 'body': json.dumps(result)}
except Exception as e:
logger.error(f"Error: {str(e)}", exc_info=True)
return {'statusCode': 500, 'body': json.dumps({'error': str(e)})}
Exam Tip: REPORT line = first place to check. Duration close to timeout → optimize. Max Memory Used close to Memory Size → increase memory. Init Duration = cold start.