CloudWatch Logs and Logs Insights
Overview
CloudWatch Logs centralises log data from EC2, Lambda, containers, VPC Flow Logs, CloudTrail and more. Logs are grouped into log groups (one per application or component) containing log streams (one per source such as an instance or container).
Imagine a library where every machine drops its diary into a labelled shelf. Without it you would SSH into each server to read files. With it you can search all diaries at once using Logs Insights, count error patterns, and even turn patterns into metrics that drive alarms.
SysOps administrators must know how to ingest logs (agent, Lambda, Firehose), control cost (retention, class), analyse (Insights, metric filters) and forward (subscription filters, export).
Key Concepts
- Hierarchy: log group -> log stream -> log events. Retention is set per log group; the default is never expire.
- Metric filters turn matching log patterns into CloudWatch metrics, which can then drive alarms.
- Logs Insights is an interactive query language (fields, filter, stats, sort, parse, limit) charged by data scanned.
- Subscription filters stream logs in real time to Kinesis Data Streams, Firehose or Lambda (and cross-account destinations).
- Export to S3 (CreateExportTask) is batch and can take up to 12 hours; use Firehose subscription for continuous delivery.
- Log classes: Standard and Infrequent Access (cheaper ingestion, fewer features).
- Logs can be encrypted with KMS and protected with data protection policies that mask sensitive data.
- Embedded Metric Format (EMF) lets apps emit metrics inside structured logs.
Detailed Notes
Getting logs in
| Source | How |
|---|---|
| EC2 / on-premises | CloudWatch agent (logs_collected section) |
| Lambda | Automatic; needs logs:CreateLogGroup/PutLogEvents in the execution role |
| ECS/EKS | awslogs driver, Fluent Bit / Container Insights |
| VPC Flow Logs, Route 53 query logs, API Gateway | Native publishing option to a log group |
| CloudTrail | Optional delivery of trail events to a log group |
Retention and cost control
aws logs put-retention-policy --log-group-name /prod/web --retention-in-days 30
aws logs describe-log-groups --query "logGroups[?retentionInDays==null].logGroupName"
The second command finds groups that never expire – a common unexpected cost. Archive long-term data to S3 and Glacier.
Metric filters
aws logs put-metric-filter --log-group-name /prod/web \
--filter-name 5xxErrors \
--filter-pattern '[ip, id, user, ts, req, status=5*, size]' \
--metric-transformations metricName=Http5xx,metricNamespace=MyApp,metricValue=1,defaultValue=0
Metric filters apply only to events ingested after creation – they do not back-fill historic data.
Logs Insights queries
fields @timestamp, @message
| filter @message like /ERROR/
| stats count(*) as errors by bin(5m)
| sort errors desc
| limit 20
# Lambda: slowest invocations
filter @type = "REPORT"
| stats avg(@duration), max(@duration), pct(@duration, 95) by bin(15m)
You can query multiple log groups and save queries; results can be added to dashboards.
Subscription filters and cross-account
aws logs put-subscription-filter --log-group-name /prod/web \
--filter-name to-firehose --filter-pattern "" \
--destination-arn arn:aws:firehose:us-east-1:111122223333:deliverystream/logs-to-s3 \
--role-arn arn:aws:iam::111122223333:role/CWLtoFirehose
A log group supports a limited number of subscription filters (2 per group), so fan out downstream.
Contributor Insights and Live Tail
- Contributor Insights finds top-N contributors (e.g. top IPs causing errors) from log data.
- Live Tail streams logs in the console in real time for debugging.
Troubleshooting missing logs
| Symptom | Check |
|---|---|
| No log group from EC2 | Agent running? Instance role has CloudWatchAgentServerPolicy? Config file valid? |
| Lambda has no logs | Execution role missing logging permissions |
| Cannot decrypt logs | KMS key policy must allow the CloudWatch Logs service principal |
| Metric filter shows no data | Pattern mismatch, or filter created after events |
Log groups keep data forever by default, which quietly grows cost; set a retention policy per group (for example 30 days for debug logs, 365 for audit) and export or stream older data to S3.
aws logs put-retention-policy --log-group-name /app/web --retention-in-days 30
aws logs put-subscription-filter --log-group-name /app/web --filter-name to-firehose \
--filter-pattern "" --destination-arn arn:aws:firehose:us-east-1:111122223333:deliverystream/logs-to-s3 \
--role-arn arn:aws:iam::111122223333:role/CWLtoFirehose
aws logs put-data-protection-policy --log-group-identifier /app/web --policy-document file://mask-pii.json
| Feature | Purpose | Limit to remember |
|---|---|---|
| Subscription filter | Real-time stream to Kinesis, Firehose, Lambda or another account | Up to two subscription filters per log group |
| Export task | Batch export to S3 | Can take up to 12 hours; not real time |
| Embedded Metric Format (EMF) | Emit custom metrics from JSON log lines without PutMetricData calls | Lambda and containers use it heavily |
| Data protection policy | Detect and mask PII/credentials in logs | Masked values appear as asterisks |
| Log classes | Standard vs Infrequent Access (cheaper ingestion, fewer features) | Choose at log group creation |
| Contributor Insights | Top-N contributors such as noisy client IPs | Rules run on JSON/CLF logs |
Query tips for Insights: restrict the time range and select only the needed log groups because you are charged per GB scanned; use parse to extract fields from plain text, stats with bin() for time series, and save frequent queries. If a query returns nothing, confirm fields are JSON-discovered, the time window covers the events and the log group retention has not deleted them.
Real World Example
Scenario – finding the cause of intermittent 502s. An ecommerce site reports random 502 errors. The ops engineer opens Logs Insights across the web and API log groups, filters on status=502, and groups by upstream instance. One container accounts for 90% of failures.
She creates a metric filter for 502s, an alarm that notifies the team, and a subscription filter that streams logs through Firehose to S3 for long-term analysis in Athena. Retention on all groups is set to 30 days, cutting the monthly logs bill by 60%.
Architecture Diagram
- 1Agents and managed services send events to log groups.
- 2Retention policies expire old data to control cost.
- 3Metric filters convert patterns such as 5xx into metrics and alarms.
- 4A subscription filter streams data through Firehose to S3 for archive and analytics.
Best Practices
- ✓Set retention on every log group (including Lambda groups created automatically) via IaC.
- ✓Emit structured JSON logs so Insights can query fields without regex.
- ✓Use metric filters or EMF for application KPIs, then alarm on them.
- ✓Encrypt sensitive groups with KMS and mask secrets with data protection policies.
- ✓Stream to S3 via Firehose for archive instead of one-off export tasks.
Common Interview Questions
Exam Tips
SOA-C03 focus
- Logs default retention is never expire – set retention to reduce cost.
- Turn log patterns into alarms -> metric filter. Ad-hoc search -> Logs Insights.
- Real-time forwarding to another destination -> subscription filter (Kinesis, Firehose, Lambda).
- Instance not shipping logs -> verify agent, IAM instance profile and agent config.
Finished this lesson?
0 of 46 lessons done · 0% of the course

