CloudWatch Logs, Logs Insights, Metric Filters and Subscriptions: Centralized Log Management
Logs Concepts
| Term | Meaning |
| Log group | Collection of streams with shared retention, encryption, access and metric filters. Usually one per application or component |
| Log stream | Sequence of events from one source (instance, container, Lambda instance) |
| Log event | Timestamp plus message (max 256 KB) |
| Retention | 1 day to 10 years or never expire (default). Set it |
| Log classes | Standard and Infrequent Access (cheaper ingestion, fewer features) |
How Logs Get There
| Source | Method |
| EC2 / on-premises | CloudWatch agent (logs_collected), needs IAM role |
| Lambda | Automatic to /aws/lambda/<name>. Role needs logs:CreateLogGroup/Stream, PutLogEvents |
| ECS | awslogs driver or FireLens (Fluent Bit) |
| EKS | Fluent Bit or CloudWatch Observability add-on |
| VPC Flow Logs, Route 53 resolver, API Gateway, RDS, CloudTrail, WAF | Built-in log destination options |
| Your code | SDK PutLogEvents, or write JSON to stdout/stderr and let the platform ship it |
- Structured JSON logs are far easier to query and filter than free text
- Do not log secrets or personal data. Use data protection policies to detect and mask sensitive data (emails, card numbers, keys)
Search: Filter Patterns and Live Tail
bash
aws logs filter-log-events --log-group-name /prod/web/nginx-error --filter-pattern "ERROR" --start-time $(date -d '1 hour ago' +%s000)
aws logs tail /aws/lambda/checkout --follow --since 15m --filter-pattern '{ $.level = "ERROR" }'
aws logs put-retention-policy --log-group-name /prod/web/nginx-error --retention-in-days 30
- Filter pattern syntax: terms (
ERROR), multiple terms (ERROR timeout, AND), ?ERROR ?WARN (OR), -debug (exclude), JSON ({ $.status = 500 }), space-delimited ([ip, user, ts, req, status=5*, size])
- Live Tail streams logs in the console in real time for debugging
CloudWatch Logs Insights
A query language to analyze logs interactively: it auto-discovers fields in JSON and AWS service logs, works across multiple log groups, and charts results. You pay per GB scanned, so narrow the time range and log groups.
text
# Top 10 error messages in the last hour
fields @timestamp, @message
| filter @message like /ERROR/
| stats count(*) as errors by @message
| sort errors desc
| limit 10
# 5xx rate per 5 minutes from JSON ALB-style logs
fields @timestamp, status
| filter status >= 500
| stats count() as c by bin(5m)
# Slowest requests
fields @timestamp, path, duration_ms
| sort duration_ms desc
| limit 20
# Parse text logs
parse @message "user=* action=* status=*" as user, action, status
| stats count() by action, status
# Lambda cold starts
filter @type = "REPORT" and ispresent(@initDuration)
| stats count() as coldStarts, avg(@initDuration) by bin(1h)
- Commands:
fields, filter, stats, sort, limit, parse, dedup, display, pattern (find log patterns), diff
- Save queries, add them to dashboards, and run them from the CLI with
start-query and get-query-results
- Natural-language query generation can help write queries, but always check the result
Metric Filters: Logs into Metrics and Alarms
bash
aws logs put-metric-filter --log-group-name /prod/web/nginx-error --filter-name error-count --filter-pattern "ERROR" \
--metric-transformations metricName=NginxErrors,metricNamespace=Shop,metricValue=1,defaultValue=0
aws cloudwatch put-metric-alarm --alarm-name nginx-errors --namespace Shop --metric-name NginxErrors --statistic Sum --period 300 \
--evaluation-periods 1 --threshold 20 --comparison-operator GreaterThanThreshold --alarm-actions $SNS --treat-missing-data notBreaching
- Metric filters only process new events after creation (not past data)
- Typical uses: count errors, failed SSH logins (
Failed password), root console logins (from CloudTrail logs), CIS benchmark alarms
- Create the metric filter on the CloudTrail log group for unauthorized API calls, IAM policy changes and security group changes
Subscription Filters: Stream Logs Elsewhere
| Destination | Use |
| Lambda | Custom processing, alert enrichment |
| Kinesis Data Streams | Real-time processing and fan-out |
| Kinesis Data Firehose | Deliver to S3, OpenSearch, Splunk, Redshift (with transformation) |
| Cross-account destination | Send logs to a central logging account |
bash
aws logs put-subscription-filter --log-group-name /prod/web/nginx-error --filter-name to-firehose --filter-pattern "" \
--destination-arn arn:aws:firehose:ap-south-1:111111111111:deliverystream/central-logs --role-arn arn:aws:iam::111111111111:role/CWLtoFirehose
- Each log group supports a limited number of subscription filters (2 per group by default)
- Data arrives base64 + gzip encoded in Lambda events: decode first
Export and Archive
- Export task (
create-export-task) copies a time range to S3. It is not real time and runs one task at a time per account
- For continuous archive use subscription → Firehose → S3
- Use S3 lifecycle to move old logs to cheaper storage. Query with Athena
Contributor Insights and Anomaly Detection
- Contributor Insights ranks top contributors (top IPs, top error callers, top DynamoDB keys) with rules over logs
- Log anomaly detection finds unusual patterns in a log group automatically
Security and Access
- Encrypt log groups with a KMS key (key policy must allow the CloudWatch Logs service)
- Restrict
logs:* and use resource policies for services that write logs (for example Route 53, Flow Logs)
- Logs are also audited by CloudTrail
Troubleshooting: Logs Not Appearing
| Cause | Fix |
| Agent not running or bad config path | Check agent status and amazon-cloudwatch-agent.log |
| Missing permissions | Add logs:CreateLogGroup, CreateLogStream, PutLogEvents to the role |
| No network path | NAT gateway or logs VPC endpoint |
| Log file rotates or wrong glob | Use correct file_path pattern, check file read permission for cwagent |
| Lambda never invoked or role lacks logging | Check invocation and execution role |
| Time range or Region mismatch in console | Choose the right Region and period |
Throttled PutLogEvents | Reduce batch frequency or spread across streams |
| KMS key blocks writing | Fix key policy |
Practice Tasks
- Ship an nginx error log with the agent and set 30-day retention
- Write Logs Insights queries for top errors and slowest requests
- Create a metric filter and alarm for failed SSH logins
- Subscribe a log group to Firehose that delivers to S3
- Add a data protection policy that masks email addresses
Conclusion
Centralize logs in CloudWatch Logs with retention and encryption, query them with Logs Insights, turn patterns into metrics and alarms using metric filters, stream to S3 or other systems with subscription filters, and troubleshoot missing logs by checking agent, permissions, network and Region.
Quick Summary: concepts; ingestion; search; Logs Insights; metric filters; subscriptions; export; security; troubleshooting.