0Pricing
Serverless Backend with AWS Lambda & API Gateway · 课时

使用 CloudWatch 进行日志记录与监控

在 Lambda 函数中实施完善的日志记录,并使用 AWS CloudWatch 监控其性能和错误

使用 CloudWatch 进行日志记录与监控 是 CoddyKit 上的免费 Serverless Backend with AWS Lambda & API Gateway 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Serverless Backend with AWS Lambda & API Gateway 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Serverless Backend with AWS Lambda & API Gateway 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Why Log & Monitor Lambda?

When your Lambda functions run in the cloud, you can't just attach a debugger. This is where logging and monitoring become incredibly important!

They help you understand what your function is doing, debug issues, and ensure it's performing well.

Meet AWS CloudWatch

AWS CloudWatch is the central observability service for AWS. It collects and processes raw data from AWS services (like Lambda) into readable metrics and logs.

  • CloudWatch Logs: Stores your function's text output.
  • CloudWatch Metrics: Gathers performance data (invocations, errors, duration).
  • CloudWatch Alarms: Notifies you when metrics cross defined thresholds.

Lambda Logs Automatically

Good news! AWS Lambda automatically integrates with CloudWatch Logs. Any output your function sends to stdout (standard output) or stderr (standard error) will be captured.

This means simple print() statements in Python, or console.log() in Node.js, will show up in CloudWatch Logs.

Python Logging Module

While print() works, for more robust logging in Python, you should use the built-in logging module. It allows you to:

  • Set different log levels (DEBUG, INFO, WARNING, ERROR, CRITICAL).
  • Include timestamps and other metadata automatically.
  • Format your log messages consistently.

Basic Lambda Logging Demo

Try running this simple Python Lambda function. Notice how both print() and logger.info() messages are captured. In a real Lambda, these would appear in CloudWatch Logs.

import json
import logging

# Configure logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)

def lambda_handler(event, context):
    # Messages from print() go to CloudWatch Logs
    print("Starting Lambda execution!")

    # Messages from the logging module also go to CloudWatch Logs
    logger.info("This is an informational log message.")

    # Log the event received by the Lambda function
    logger.info(f"Received event: {json.dumps(event)}")

    # Simulate some work
    result = "Processing complete."
    logger.info(f"Function result: {result}")

    return {
        'statusCode': 200,
        'body': json.dumps(result)
    }

CloudWatch Log Structure

When Lambda sends logs to CloudWatch, they are organized in a specific way:

  • Log Group: A container for logs from a specific application or service. For Lambda, it's typically /aws/lambda/YOUR_FUNCTION_NAME.
  • Log Stream: Within a Log Group, each instance or invocation of your Lambda function creates a new Log Stream to store its logs.

Viewing Your Lambda Logs

You can access your function's logs in the AWS Console:

  1. Navigate to the Lambda service.
  2. Select your function.
  3. Go to the 'Monitor' tab.
  4. Click 'View logs in CloudWatch' to see the Log Group and Streams.

Here you can filter, search, and analyze your log data to debug issues.

Monitoring Lambda Metrics

Beyond logs, CloudWatch automatically collects metrics for your Lambda functions, giving you insights into their performance and health without any extra code.

Key metrics include:

  • Invocations: Total number of times your function was triggered.
  • Errors: Count of failed invocations.
  • Duration: Execution time of your function.
  • Throttles: When Lambda denied an invocation due to concurrency limits.

Setting Up CloudWatch Alarms

CloudWatch Alarms allow you to set up notifications or actions based on metric thresholds. For example, you can create an alarm that:

  • Triggers if the 'Errors' metric for your function is greater than 0 for 5 minutes.
  • Sends a notification via Amazon SNS (Simple Notification Service) to your email or an alerting system.

This is crucial for proactive monitoring!

CloudWatch Capabilities Check

CloudWatch is a powerful tool for serverless operations. Which of the following are capabilities of AWS CloudWatch when monitoring Lambda functions?

Lesson Summary

Great job! You've learned how critical logging and monitoring are for serverless applications, especially with AWS Lambda.

  • Lambda seamlessly integrates with CloudWatch Logs for capturing output.
  • The Python logging module provides robust logging.
  • CloudWatch Metrics give you insights into function performance.
  • CloudWatch Alarms enable proactive alerts based on these metrics.

These tools are essential for debugging, performance tuning, and maintaining healthy serverless backends.

常见问题解答

「使用 CloudWatch 进行日志记录与监控」课时是免费的吗?

是的 — 「使用 CloudWatch 进行日志记录与监控」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Serverless Backend with AWS Lambda & API Gateway 课程的其余内容,请升级到 CoddyKit PRO。 Serverless Backend with AWS Lambda & API Gateway 课程共包含 4 节课。

「使用 CloudWatch 进行日志记录与监控」这节课中我会学到什么?

在 Lambda 函数中实施完善的日志记录,并使用 AWS CloudWatch 监控其性能和错误 你通过在浏览器中直接运行的动手代码来练习 Serverless Backend with AWS Lambda & API Gateway,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Serverless Backend with AWS Lambda & API Gateway 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Serverless Backend with AWS Lambda & API Gateway 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「使用 CloudWatch 进行日志记录与监控」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Serverless Backend with AWS Lambda & API Gateway 课中编写并运行代码吗?

能。每节 Serverless Backend with AWS Lambda & API Gateway 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. Lambda 运行时与处理程序
  2. 环境变量与层
  3. 使用 CloudWatch 进行日志记录与监控
  4. 错误处理、重试与死信队列
← 返回 Serverless Backend with AWS Lambda & API Gateway