CloudWatch Logs, Logs Insights, Metric Filters and Subscriptions: Centralized Log Management

AWS SysOps Associate 50 min min read Updated: Nov 17, 2026 Intermediate
CloudWatch Logs, Logs Insights, Metric Filters and Subscriptions: Centralized Log Management
Intermediate Topic 2 of 4

Logs Concepts

TermMeaning
Log groupCollection of streams with shared retention, encryption, access and metric filters. Usually one per application or component
Log streamSequence of events from one source (instance, container, Lambda instance)
Log eventTimestamp plus message (max 256 KB)
Retention1 day to 10 years or never expire (default). Set it
Log classesStandard and Infrequent Access (cheaper ingestion, fewer features)

How Logs Get There

SourceMethod
EC2 / on-premisesCloudWatch agent (logs_collected), needs IAM role
LambdaAutomatic to /aws/lambda/<name>. Role needs logs:CreateLogGroup/Stream, PutLogEvents
ECSawslogs driver or FireLens (Fluent Bit)
EKSFluent Bit or CloudWatch Observability add-on
VPC Flow Logs, Route 53 resolver, API Gateway, RDS, CloudTrail, WAFBuilt-in log destination options
Your codeSDK 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

DestinationUse
LambdaCustom processing, alert enrichment
Kinesis Data StreamsReal-time processing and fan-out
Kinesis Data FirehoseDeliver to S3, OpenSearch, Splunk, Redshift (with transformation)
Cross-account destinationSend 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

CauseFix
Agent not running or bad config pathCheck agent status and amazon-cloudwatch-agent.log
Missing permissionsAdd logs:CreateLogGroup, CreateLogStream, PutLogEvents to the role
No network pathNAT gateway or logs VPC endpoint
Log file rotates or wrong globUse correct file_path pattern, check file read permission for cwagent
Lambda never invoked or role lacks loggingCheck invocation and execution role
Time range or Region mismatch in consoleChoose the right Region and period
Throttled PutLogEventsReduce batch frequency or spread across streams
KMS key blocks writingFix key policy

Practice Tasks

  1. Ship an nginx error log with the agent and set 30-day retention
  2. Write Logs Insights queries for top errors and slowest requests
  3. Create a metric filter and alarm for failed SSH logins
  4. Subscribe a log group to Firehose that delivers to S3
  5. 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.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators