CloudWatch Metrics, Logs and Alarms
Overview
Amazon CloudWatch is the observability hub of AWS. It collects metrics (numbers over time), logs (text events), alarms (automated reactions) and dashboards (visualisations). Almost every AWS service publishes to it, and your application can add its own data.
Think of a car dashboard. Metrics are the gauges (speed, fuel), logs are the black-box recorder of everything that happened, and alarms are the warning lights and beeps that tell you to act before the engine fails.
You need to know default vs custom metrics, how to publish them from code, how to query logs with Logs Insights, and how alarms trigger actions such as SNS notifications, Auto Scaling or EC2 recovery.
Key Concepts
- Metrics are identified by namespace, name and dimensions; standard resolution is 1 minute (EC2 basic monitoring is 5 minutes, detailed is 1 minute); high-resolution custom metrics go down to 1 second.
- Custom metrics are published with
PutMetricDataor the Embedded Metric Format (EMF) written to logs; memory and disk usage on EC2 need the CloudWatch agent. - Alarms have states OK, ALARM, INSUFFICIENT_DATA; actions: SNS, Auto Scaling, EC2 actions, Systems Manager; composite alarms combine alarms to reduce noise.
- CloudWatch Logs organises data into log groups (retention, encryption, subscriptions) and log streams; default retention is never expire, so set it.
- Metric filters turn log patterns into metrics (for example count of
ERROR) that can drive alarms. - Logs Insights runs a SQL-like query language over log groups; subscription filters stream logs to Lambda, Kinesis or Firehose in near real time.
- Lambda automatically sends logs to
/aws/lambda/<name>and publishes metrics: Invocations, Errors, Duration, Throttles, ConcurrentExecutions, IteratorAge. - Synthetics canaries test endpoints, RUM captures real user data, and Contributor Insights finds top contributors.
Detailed Notes
Metrics worth knowing
| Service | Key metrics |
|---|---|
| Lambda | Errors, Throttles, Duration, ConcurrentExecutions, IteratorAge |
| API Gateway | 4XXError, 5XXError, Latency, IntegrationLatency, Count |
| SQS | ApproximateNumberOfMessagesVisible, ApproximateAgeOfOldestMessage |
| DynamoDB | ConsumedRead/WriteCapacityUnits, ThrottledRequests, SystemErrors |
| ALB | HTTPCode_Target_5XX_Count, TargetResponseTime, UnHealthyHostCount |
| EC2 | CPUUtilization, StatusCheckFailed (memory needs the agent) |
Publishing a custom metric
import boto3, time
cw = boto3.client("cloudwatch")
cw.put_metric_data(
Namespace="Shop/Orders",
MetricData=[{
"MetricName": "OrderValue",
"Dimensions": [{"Name": "Stage", "Value": "prod"}],
"Timestamp": time.time(),
"Value": 129.5,
"Unit": "Count",
"StorageResolution": 1, # high resolution (1 second)
}],
)
For Lambda, writing a structured EMF log line creates metrics without API calls or added latency:
import json, time
def emit(name, value):
print(json.dumps({
"_aws": {"Timestamp": int(time.time() * 1000),
"CloudWatchMetrics": [{"Namespace": "Shop/Orders",
"Dimensions": [["Stage"]],
"Metrics": [{"Name": name, "Unit": "Count"}]}]},
"Stage": "prod", name: value,
}))
Alarms
aws cloudwatch put-metric-alarm --alarm-name orders-fn-errors \
--namespace AWS/Lambda --metric-name Errors \
--dimensions Name=FunctionName,Value=OrdersFn \
--statistic Sum --period 60 --evaluation-periods 3 --datapoints-to-alarm 2 \
--threshold 5 --comparison-operator GreaterThanOrEqualToThreshold \
--treat-missing-data notBreaching \
--alarm-actions arn:aws:sns:eu-west-1:111122223333:ops-alerts
datapoints-to-alarm implements "M out of N" evaluation to reduce flapping. Anomaly detection alarms use ML bands instead of fixed thresholds.
Logs Insights queries
fields @timestamp, @message, @requestId
| filter @message like /ERROR/
| stats count() as errors by bin(5m)
| sort errors desc
filter @type = "REPORT"
| stats avg(@duration), max(@maxMemoryUsed / 1024 / 1024) as maxMemMB, count(*) as invocations by bin(1h)
The Lambda REPORT line includes duration, billed duration, memory size and max memory used, perfect for right-sizing and spotting cold starts (@initDuration).
Structured logging
Log JSON so fields can be queried:
console.log(JSON.stringify({ level: "error", orderId, msg: "payment failed", err: e.message }));
AWS Lambda Powertools (Python, TypeScript, Java, .NET) adds structured logging, metrics (EMF), tracing and idempotency utilities.
Log export and retention
| Need | Option |
|---|---|
| Long-term archive | Export to S3 (CreateExportTask) or subscription to Firehose |
| Real-time processing | Subscription filter to Lambda/Kinesis |
| Cross-account central logging | Subscriptions to a destination in a central account |
| Cost control | Set retention, reduce verbosity, use Infrequent Access log class |
CloudWatch agent
Install the unified agent on EC2/on-premises to collect memory, disk, swap and custom log files. Configure it with a JSON file stored in Parameter Store.
Alarms vs EventBridge
Use alarms for metric thresholds; use EventBridge for discrete events such as state changes and API calls.
Dashboards
Dashboards can combine metrics across Regions and accounts, with annotations and automatic refresh. Create them as code with CloudFormation AWS::CloudWatch::Dashboard.
Custom metrics, EMF and Logs Insights
import json, boto3
cw = boto3.client("cloudwatch")
cw.put_metric_data(Namespace="Orders", MetricData=[{
"MetricName": "OrdersPlaced", "Dimensions": [{"Name": "Stage", "Value": "prod"}],
"Value": 1, "Unit": "Count", "StorageResolution": 1}]) # 1 = high resolution
# Embedded Metric Format: a log line that CloudWatch turns into a metric
print(json.dumps({"_aws": {"Timestamp": 1735689600000, "CloudWatchMetrics": [{
"Namespace": "Orders", "Dimensions": [["Stage"]], "Metrics": [{"Name": "Latency", "Unit": "Milliseconds"}]}]},
"Stage": "prod", "Latency": 123}))
fields @timestamp, @message
| filter @message like /ERROR/
| stats count(*) as errors by bin(5m)
| sort errors desc
| Concept | Detail |
|---|---|
| Standard resolution | 1-minute granularity; high resolution down to 1 second |
| Alarm states | OK, ALARM, INSUFFICIENT_DATA; configure missing-data treatment |
| Composite alarms | Combine alarms with AND/OR to reduce noise |
| Metric filters | Turn log patterns into metrics |
| Subscription filters | Stream logs to Lambda, Kinesis or Firehose |
| Retention | Log groups keep data forever by default; set retention to control cost |
| Default EC2 metrics | CPU, network, disk I/O; memory and disk use need the CloudWatch agent |
Alarm actions can notify SNS, run Auto Scaling policies, or reboot or recover an EC2 instance. Use anomaly detection bands for metrics without a fixed threshold, and Contributor Insights to find top talkers in logs.
Real World Example
An e-commerce team wants to know when checkout is failing. The Lambda checkout function emits EMF metrics PaymentFailures and OrderValue; a metric filter counts ERROR log lines; a composite alarm fires only when both the error rate is high and API Gateway 5XX exceeds a threshold, notifying SNS and PagerDuty. During incidents, they use a saved Logs Insights query to group errors by requestId and trace one of them through X-Ray.
Architecture Diagram
Applications emit metrics and logs; alarms react and notify.
- 1The application writes structured logs and custom metrics.
- 2CloudWatch stores metrics and indexes logs for Insights queries.
- 3An alarm evaluates a metric against a threshold over several periods.
- 4On ALARM, an SNS action notifies the on-call engineer or triggers automation.
Best Practices
- ✓Emit structured JSON logs with request IDs and use EMF for custom metrics.
- ✓Set log retention and encrypt critical log groups.
- ✓Use M-of-N evaluation and composite alarms to reduce noise.
- ✓Alarm on symptoms (latency, error rate, queue age), not only CPU.
- ✓Define dashboards and alarms as code.
Common Interview Questions
Exam Tips
DVA-C02 focus
- Memory/disk metrics -> CloudWatch agent (custom metrics).
- Alarm states: OK, ALARM, INSUFFICIENT_DATA.
- Custom metrics without API calls from Lambda -> Embedded Metric Format.
- Search and aggregate logs -> Logs Insights; stream logs -> subscription filter.
Finished this lesson?
0 of 46 lessons done · 0% of the course

