4.1.1 Debug Code to Identify Defects

Debug Code to Identify Defects

Lambda Debugging Approaches

ApproachToolMô tả
Local testingSAM CLIsam local invoke với test events
Console testingAWS ConsoleTest events trực tiếp
LoggingCloudWatch LogsPrint/log statements
TracingX-RayEnd-to-end request tracing
Step-throughIDE debuggerLocal debugging với SAM

Common Code Defects

DefectSymptomDebug Method
Unhandled exceptionLambda error, 502CloudWatch Logs → stack trace
Wrong response formatAPI GW 502Check statusCode, body format
Missing env variableKeyError/undefinedCheck Lambda configuration
TimeoutTask timed outCheck Duration in REPORT line
Memory exceededRuntime.ExitErrorCheck 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.