CloudWatch 日志与指标
利用 Amazon CloudWatch 收集、监控并分析 Lambda 函数和其他 AWS 服务的日志与性能指标
CloudWatch 日志与指标 是 CoddyKit 上的免费 Serverless AWS Lambda Development 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Serverless AWS Lambda Development 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Serverless AWS Lambda Development 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Your Serverless Watchdog: CloudWatch
Welcome! In this lesson, we'll dive into Amazon CloudWatch, AWS's powerful monitoring and observability service. It's your eyes and ears for understanding what's happening with your AWS resources and applications.
For serverless applications built with AWS Lambda, CloudWatch is absolutely essential to ensure everything runs smoothly.
Why Monitoring Matters for Lambda
Lambda functions execute quickly and often, sometimes hundreds or thousands of times per second. Without proper visibility, it's incredibly hard to know if they're working correctly or encountering issues.
CloudWatch helps you:
- Monitor function health and performance.
- Debug errors efficiently when things go wrong.
- Optimize resource usage and control costs.
Diving into CloudWatch Logs
The first key component is CloudWatch Logs. This is where all your Lambda function's text-based output, runtime messages, and errors are stored. Think of it as a centralized place for all your application's 'print statements' and system messages.
Every time your Lambda function runs, it generates logs. These logs are automatically sent to CloudWatch Logs.
Lambda's Automatic Logging
The great news is you don't need to configure anything special for basic logging. When your Lambda function executes, anything printed to standard output (like console.log in Node.js or print() in Python) is automatically captured.
These captured messages, along with execution details (like start/end times and billing info), are then pushed to CloudWatch Logs without any extra setup from you.
Organizing Your Logs: Groups & Streams
CloudWatch Logs organizes logs into two main concepts:
- Log Group: A container for log streams that share the same retention, monitoring, and access control settings. Each Lambda function typically gets its own Log Group (e.g.,
/aws/lambda/your-function-name). - Log Stream: A sequence of log events from a single source. Each invocation or concurrent execution of your Lambda function typically creates a new log stream within its log group.
Adding Logs in Your Lambda Code
You can add custom log messages to your Lambda function code. This helps you trace execution flow, understand data, and debug issues. Here's a simple Python example using the standard logging module:
import json
import logging
# Configure logging for the Lambda function
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def lambda_handler(event, context):
logger.info("Lambda function started processing event.")
logger.info(f"Received event: {json.dumps(event)}")
message = "Hello from CoddyKit Lambda!"
logger.info(f"Preparing response: {message}")
return {
'statusCode': 200,
'body': json.dumps(message)
}
# Example of how you might test this locally
if __name__ == "__main__":
# Simulate a simple event object
test_event = {"action": "greet", "name": "Learner"}
# The 'context' object is usually provided by Lambda, we can mock it or pass None for basic tests.
result = lambda_handler(test_event, None)
print("--- Lambda Handler Output (Local Test) ---")
print(result)Introducing CloudWatch Metrics
While logs tell you what happened in detail, CloudWatch Metrics tell you how well your functions are performing. Metrics are time-ordered sets of numerical data points that represent a specific measurement.
AWS automatically collects metrics for your Lambda functions, giving you high-level insights into their operational health and performance trends.
Essential Lambda Performance Metrics
Some crucial metrics that CloudWatch automatically collects for your Lambda functions include:
- Invocations: The total number of times your function was triggered.
- Errors: The number of times your function failed during execution.
- Duration: The execution time of your function, measured in milliseconds.
- Throttles: The number of times your function invocations were limited due to concurrency limits.
Monitoring these helps you quickly identify performance bottlenecks or potential issues.
Visualizing Metrics in the Console
You can view these performance metrics as interactive graphs in the CloudWatch console. Simply navigate to the 'Metrics' section, then select 'Lambda', and choose the desired metric for your specific function.
This visual representation makes it easy to spot trends, sudden spikes, or drops in performance, allowing you to react quickly to operational changes and optimize your functions.
Quick Check: Logs vs. Metrics
Let's test your understanding of CloudWatch Logs and Metrics for AWS Lambda.
Recap: CloudWatch for Serverless Insight
We've explored how Amazon CloudWatch is your go-to service for monitoring AWS Lambda functions. You learned about:
- CloudWatch Logs: For collecting, storing, and analyzing detailed runtime messages and custom outputs from your functions.
- CloudWatch Metrics: For tracking key performance indicators like invocations, errors, duration, and throttles.
Together, logs and metrics provide a comprehensive picture of your serverless application's health and performance, empowering you to debug and optimize effectively.
常见问题解答
「CloudWatch 日志与指标」课时是免费的吗?
是的 — 「CloudWatch 日志与指标」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Serverless AWS Lambda Development 课程的其余内容,请升级到 CoddyKit PRO。 Serverless AWS Lambda Development 课程共包含 4 节课。
「CloudWatch 日志与指标」这节课中我会学到什么?
利用 Amazon CloudWatch 收集、监控并分析 Lambda 函数和其他 AWS 服务的日志与性能指标 你通过在浏览器中直接运行的动手代码来练习 Serverless AWS Lambda Development,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Serverless AWS Lambda Development 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Serverless AWS Lambda Development 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「CloudWatch 日志与指标」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Serverless AWS Lambda Development 课中编写并运行代码吗?
能。每节 Serverless AWS Lambda Development 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- CloudWatch 日志与指标
- 错误处理与重试
- 调试无服务器应用
- 自定义指标与 CloudWatch 告警