서버리스 애플리케이션 디버깅
로컬 테스트, 원격 디버깅, 문제 해결을 위한 CloudWatch 로그 해석을 비롯하여 Lambda 함수를 효과적으로 디버깅하는 기법을 알아봅니다.
서버리스 애플리케이션 디버깅은(는) CoddyKit의 무료 Serverless AWS Lambda Development 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Serverless AWS Lambda Development 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Serverless AWS Lambda Development 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Intro to Debugging Lambda
Debugging serverless applications, especially AWS Lambda functions, presents unique challenges. Unlike traditional applications, Lambdas are stateless and ephemeral.
In this lesson, we'll explore practical techniques for effectively identifying and resolving issues in your Lambda functions, from local testing to interpreting logs.
Why Serverless Debugging is Unique
Traditional debugging often involves stepping through code line-by-line using an IDE. With Lambda, this isn't always straightforward because:
- Ephemeral Nature: Functions run only when invoked, then disappear.
- Statelessness: No persistent memory between invocations.
- Distributed Systems: Issues can arise from interactions between many services.
We rely heavily on logs, metrics, and tracing to understand what's happening.
Local Testing with SAM CLI
One of the most effective ways to debug is to test your Lambda functions locally before deploying them to AWS.
The AWS Serverless Application Model (SAM) CLI allows you to invoke your Lambda functions on your local machine, simulating the AWS Lambda runtime environment.
- Faster feedback loop.
- Use your familiar local debugging tools.
SAM CLI Local Invoke Demo
Here's a simple Python Lambda function. For local testing, you can simulate an event and context. Try running it!
import json
def lambda_handler(event, context):
message = event.get('message', 'Hello from Lambda!')
print(f"Received event: {json.dumps(event)}")
print(f"Processing message: {message}")
return {
'statusCode': 200,
'body': json.dumps({'response': message})
}
# This block allows local execution
if __name__ == '__main__':
# Simulate an event
test_event = {'message': 'Local debug test'}
# Simulate a context object
test_context = type('obj', (object,), {'invoked_function_arn': 'local'})()
response = lambda_handler(test_event, test_context)
print("\n--- Lambda Response ---")
print(json.dumps(response, indent=2))
CloudWatch Logs for Debugging
Once your Lambda is deployed, Amazon CloudWatch Logs becomes your primary tool for understanding its behavior and debugging issues.
Every time your Lambda function is invoked, logs are sent to a dedicated log group. Each invocation gets a unique Request ID, which helps trace its execution.
- Log Groups: Contain logs for a specific function.
- Log Streams: Specific instances of your function's logs.
Finding Issues in Logs
When an error occurs, the first place to look is CloudWatch Logs. You can:
- Filter Logs: Search for keywords like "ERROR", "Exception", or specific messages.
- Log Insights: Use powerful query language to analyze logs, group errors, and identify trends.
- Request ID: Use the Request ID from the invocation to find all logs related to a specific execution.
Always check the full stack trace for detailed error information.
Debugging with Log Statements
The simplest yet most powerful debugging technique for Lambda is using print() (Python) or console.log() (Node.js) statements.
By strategically adding log statements, you can track variable values, execution paths, and function state at different points in your code. Let's see an example:
import json
def calculate_discount(price, discount_percentage):
print(f"DEBUG: Initial price: {price}")
if not isinstance(price, (int, float)) or price < 0:
raise ValueError("Price must be non-negative.")
if not isinstance(discount_percentage, (int, float)) or not (0 <= discount_percentage <= 100):
raise ValueError("Discount must be between 0 and 100.")
discount_amount = price * (discount_percentage / 100)
final_price = price - discount_amount
print(f"DEBUG: Final price: {final_price}")
return final_price
def lambda_handler(event, context):
try:
data = json.loads(event['body'])
price = data['price']
discount = data['discount']
final_price = calculate_discount(price, discount)
return {
'statusCode': 200,
'body': json.dumps({'originalPrice': price, 'finalPrice': final_price})
}
except Exception as e:
print(f"ERROR: An error occurred: {e}")
return {
'statusCode': 400,
'body': json.dumps({'error': str(e)})
}
if __name__ == '__main__':
# Test case 1: Valid input
test_event_1 = {'body': json.dumps({'price': 100, 'discount': 10})}
response_1 = lambda_handler(test_event_1, None)
print("\n--- Test Case 1 Response ---")
print(json.dumps(response_1, indent=2))
# Test case 2: Invalid discount
test_event_2 = {'body': json.dumps({'price': 50, 'discount': 110})}
response_2 = lambda_handler(test_event_2, None)
print("\n--- Test Case 2 Response ---")
print(json.dumps(response_2, indent=2))
Understanding Invocation Errors
Lambda functions can fail for various reasons. It's crucial to distinguish between different error types:
- Function Errors: Your code threw an unhandled exception. These appear in CloudWatch Logs with a stack trace.
- Invocation Errors: Issues before your code even runs, like permissions errors or payload size limits. These might not even show up in your function's logs directly.
- Timeout Errors: Your function exceeded its configured execution time.
CloudWatch metrics and X-Ray (another lesson!) help identify these.
Tracing Request Flow
In complex serverless applications, a single request might involve multiple Lambda functions, API Gateway, SQS, DynamoDB, and more.
Understanding the flow of a request across these services is key to debugging. Use the Request ID (often propagated as x-amzn-RequestId or similar) to correlate logs across different components.
AWS X-Ray (covered in a later lesson) provides visual tracing for this purpose.
Best Practices for Debugging
To minimize debugging headaches, adopt these practices:
- Comprehensive Logging: Log inputs, outputs, and key variable states.
- Structured Logging: Use JSON logs for easier parsing and querying.
- Idempotency: Design functions to produce the same result even if invoked multiple times.
- Small Functions: Easier to isolate and test.
- Automated Testing: Unit and integration tests catch issues early.
Debugging Challenge
You have a Lambda function that processes user registration. Users report that sometimes, their registration fails, but you don't see any "ERROR" messages in CloudWatch Logs for your Lambda function.
What is the most likely reason for this, and where should you investigate first?
Recap: Debugging Serverless
We've covered essential techniques for debugging your serverless applications:
- Local testing with SAM CLI for rapid iteration.
- Using CloudWatch Logs to analyze function behavior and identify errors.
- Leveraging log statements to trace execution flow.
- Understanding different types of Lambda errors.
- Best practices for building debuggable serverless functions.
Mastering these will significantly improve your ability to build robust serverless applications.
자주 묻는 질문
“서버리스 애플리케이션 디버깅” 강의는 무료인가요?
네 — “서버리스 애플리케이션 디버깅” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Serverless AWS Lambda Development 강의 전체를 잠금 해제할 수 있습니다. Serverless AWS Lambda Development 강의에는 총 4개의 강의가 포함되어 있습니다.
“서버리스 애플리케이션 디버깅”에서 뭘 배우나요?
로컬 테스트, 원격 디버깅, 문제 해결을 위한 CloudWatch 로그 해석을 비롯하여 Lambda 함수를 효과적으로 디버깅하는 기법을 알아봅니다. 브라우저에서 직접 실행하는 실습 코드로 Serverless AWS Lambda Development을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Serverless AWS Lambda Development을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Serverless AWS Lambda Development은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“서버리스 애플리케이션 디버깅” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Serverless AWS Lambda Development 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Serverless AWS Lambda Development 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- CloudWatch 로그 및 지표
- 오류 처리 및 재시도
- 서버리스 애플리케이션 디버깅
- 사용자 지정 지표와 CloudWatch 알람