← Learning Hub
Intermediate

CloudWatch: Logs, Metrics and Alarms

Amazon CloudWatch is how you watch your systems: what happened (logs), how things are doing (metrics), and who gets told when something goes wrong (alarms).

Once your app is live, you need to know what it's doing: Is it working? Is it slow? Are errors increasing? CloudWatch collects logs (what happened), metrics (numbers over time) and alarms (alerts when numbers cross a limit). Setting these up means you hear about problems from an alert, not from an angry customer.

Logs

Lambda sends everything you print to CloudWatch Logs automatically. EC2 and containers can send their logs with the CloudWatch agent. Logs Insights lets you search them:

Example
fields @timestamp, @message
| filter @message like /ERROR/
| sort @timestamp desc
| limit 20

Metrics

Most services publish numbers every minute: EC2 CPUUtilization, Lambda Errors and Duration, ALB HTTPCode_Target_5XX_Count, DynamoDB ThrottledRequests. Put the important ones on a dashboard.

Alarms

  • Pick a metric, e.g. Lambda Errors.
  • Set a rule: Sum > 5 within 5 minutes.
  • Choose an action: send a message to an SNS topic that emails or texts you, or tell an Auto Scaling group to add servers.
Example
aws cloudwatch put-metric-alarm \
  --alarm-name orders-api-errors \
  --namespace AWS/Lambda --metric-name Errors \
  --dimensions Name=FunctionName,Value=orders-api \
  --statistic Sum --period 300 --evaluation-periods 1 \
  --threshold 5 --comparison-operator GreaterThanThreshold \
  --alarm-actions arn:aws:sns:ap-south-1:123456789012:ops-alerts
Set a log retention period (for example 30 days) on each log group. By default logs are kept forever, and you keep paying for them.
Also create an AWS Budgets alert on your account, so you get an email before your bill grows.
Key points
  • Logs record what happened; Logs Insights searches them.
  • Metrics track numbers like CPU, errors and latency.
  • Alarms notify you through SNS when limits are crossed.
  • Set log retention to control cost.

📝 Test yourself

1. Where does a Lambda function's print() output go?
2. What can a CloudWatch alarm do when it fires?
3. Fill in what you should set on log groups to control cost:
log period