Ведение журналов и мониторинг с CloudWatch
Реализуйте надёжное ведение журналов в функциях Lambda и отслеживайте их производительность и ошибки с помощью AWS CloudWatch
«Ведение журналов и мониторинг с CloudWatch» — бесплатный урок Serverless Backend with AWS Lambda & API Gateway на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения 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:
- Navigate to the Lambda service.
- Select your function.
- Go to the 'Monitor' tab.
- 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
loggingmodule 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» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс 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 с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Serverless Backend with AWS Lambda & API Gateway?
Предыдущий опыт не требуется. Serverless Backend with AWS Lambda & API Gateway на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.
Сколько времени занимает урок «Ведение журналов и мониторинг с CloudWatch»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Serverless Backend with AWS Lambda & API Gateway?
Да. Каждый урок Serverless Backend with AWS Lambda & API Gateway включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Среда выполнения и обработчик Lambda
- Переменные среды и слои
- Ведение журналов и мониторинг с CloudWatch
- Обработка ошибок, повторные попытки и очереди недоставленных сообщений