0
0
AwsHow-ToBeginner · 4 min read

How to Monitor AWS Lambda with CloudWatch Metrics and Logs

To monitor AWS Lambda with CloudWatch, enable CloudWatch Logs to capture function logs and use CloudWatch Metrics to track invocation counts, errors, and duration. You can view these metrics in the AWS Console or create alarms to get notified on issues.
📐

Syntax

Monitoring Lambda with CloudWatch involves two main parts:

  • CloudWatch Logs: Lambda automatically sends logs to CloudWatch Logs when enabled.
  • CloudWatch Metrics: Lambda publishes metrics like Invocations, Errors, and Duration to CloudWatch Metrics.

You can access these using the AWS Console, AWS CLI, or SDKs.

bash
aws lambda update-function-configuration --function-name MyFunction --log-type Tail

# To create a CloudWatch alarm for errors
aws cloudwatch put-metric-alarm --alarm-name LambdaErrorAlarm --metric-name Errors --namespace AWS/Lambda --statistic Sum --period 300 --threshold 1 --comparison-operator GreaterThanOrEqualToThreshold --dimensions Name=FunctionName,Value=MyFunction --evaluation-periods 1 --alarm-actions arn:aws:sns:region:account-id:my-sns-topic
💻

Example

This example shows how to create a CloudWatch alarm that triggers when your Lambda function has one or more errors in 5 minutes.

bash
aws cloudwatch put-metric-alarm \
  --alarm-name LambdaErrorAlarm \
  --metric-name Errors \
  --namespace AWS/Lambda \
  --statistic Sum \
  --period 300 \
  --threshold 1 \
  --comparison-operator GreaterThanOrEqualToThreshold \
  --dimensions Name=FunctionName,Value=MyFunction \
  --evaluation-periods 1 \
  --alarm-actions arn:aws:sns:us-east-1:123456789012:NotifyMe
Output
Successfully created alarm LambdaErrorAlarm
⚠️

Common Pitfalls

  • Not enabling CloudWatch Logs in Lambda configuration, so no logs appear.
  • Confusing Errors metric with Throttles or Invocations.
  • Setting alarm thresholds too low or too high, causing false alerts or missed issues.
  • Not attaching proper IAM permissions for Lambda to write logs or for users to read metrics.
bash
## Wrong: No logs enabled, so no monitoring data
aws lambda update-function-configuration --function-name MyFunction --log-type None

## Right: Enable logs for monitoring
aws lambda update-function-configuration --function-name MyFunction --log-type Tail
📊

Quick Reference

Key CloudWatch metrics for Lambda:

MetricDescription
InvocationsNumber of times your function is called
ErrorsNumber of failed executions
DurationExecution time in milliseconds
ThrottlesNumber of invocation requests throttled
IteratorAgeAge of last record for stream-based invocations

Key Takeaways

Enable CloudWatch Logs in Lambda to capture detailed execution logs.
Use CloudWatch Metrics like Errors and Duration to track function health.
Create CloudWatch Alarms to get notified on errors or performance issues.
Ensure proper IAM permissions for Lambda and monitoring users.
Check metrics regularly to maintain Lambda function reliability.