SkillSprout
Chapter 5 · Lesson 2
Advanced
7 min read

CloudWatch Logs, Metric Filters and Logs Insights

Overview

CloudWatch Logs stores and indexes log data from applications, AWS services and agents. Logs are organised into log groups (a collection with shared retention, encryption and access) containing log streams (a sequence from one source such as an instance or Lambda container).

Think of a newsroom archive: each publication has its own filing cabinet (log group), each issue a folder (stream), and you can search every cabinet at once with a powerful query tool (Logs Insights). You can also tell the clerk to ring a bell whenever certain words appear (metric filters) or to photocopy every page to another office (subscription filters).

For DOP-C02 you must know ingestion methods, retention and encryption, metric filters that turn logs into alarms, subscription filters that stream logs to Lambda, Kinesis or Firehose, Logs Insights query language and cross-account log aggregation.

Key Concepts

  • Log groups have retention (1 day to 10 years or never expire; default never expire), KMS encryption and resource policies.
  • Ingestion: CloudWatch agent, awslogs/Fluent Bit / FireLens, Lambda (automatic), VPC Flow Logs, Route 53, API Gateway, CloudTrail and the PutLogEvents API.
  • Metric filters extract numbers or counts from matching log events to create CloudWatch metrics (not retroactive).
  • Subscription filters stream matching events in near real time to Kinesis Data Streams, Firehose, Lambda or OpenSearch; each log group supports up to 2 filters.
  • Logs Insights queries with fields, filter, stats, parse, sort, limit across multiple log groups and Regions in one account.
  • Cross-account log delivery uses a destination (backed by Kinesis) with a resource policy in the receiving account, or CloudWatch cross-account observability.
  • 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), data protection policies (masking PII) and Live Tail extend functionality.

Detailed Notes

Collecting logs

SourceMechanism
EC2 / on-premisesUnified CloudWatch agent config (logs.logs_collected.files)
LambdaAutomatic to /aws/lambda/<function> (needs permissions on the execution role)
ECS / Fargateawslogs driver or FireLens (Fluent Bit) to multiple destinations
EKSFluent Bit / CloudWatch Container Insights
NetworkVPC Flow Logs to CloudWatch Logs or S3
AuditCloudTrail to CloudWatch Logs for alarms on API calls
json
{
  "logs": {
    "logs_collected": {
      "files": {
        "collect_list": [
          { "file_path": "/var/log/app/*.log", "log_group_name": "/prod/orders/app",
            "log_stream_name": "{instance_id}", "retention_in_days": 30 }
        ]
      }
    }
  }
}

Metric filters

bash
aws logs put-metric-filter --log-group-name /prod/orders/app \
  --filter-name PaymentErrors \
  --filter-pattern '{ $.level = "ERROR" && $.component = "payment" }' \
  --metric-transformations metricName=PaymentErrors,metricNamespace=Orders,metricValue=1,defaultValue=0

Patterns support text terms, JSON ({ $.field = value }) and space-delimited formats. The filter only counts events after it is created. The CIS benchmark pattern for CloudTrail uses metric filters plus alarms for root login and IAM policy changes.

Subscription filters

bash
aws logs put-subscription-filter --log-group-name /prod/orders/app \
  --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/cwl-to-firehose

Delivered data is base64 encoded and gzip compressed; a Lambda destination must decompress it. Use a Kinesis stream when several consumers need the stream, Firehose for S3/OpenSearch/Splunk delivery, Lambda for custom processing or alerts.

Cross-account and cross-Region aggregation

bash
# Receiving (security) account
aws logs put-destination --destination-name central-logs \
  --target-arn arn:aws:kinesis:us-east-1:999988887777:stream/central-logs \
  --role-arn arn:aws:iam::999988887777:role/cwl-to-kinesis
aws logs put-destination-policy --destination-name central-logs \
  --access-policy file://allow-org.json   # Condition: aws:PrincipalOrgID

Senders create a subscription filter pointing at the destination ARN. For simpler multi-account dashboards, CloudWatch cross-account observability links source accounts to a monitoring account through the Observability Access Manager (OAM), sharing metrics, logs, traces and Application Insights without copying data.

Logs Insights queries

text
fields @timestamp, @message, @logStream
| filter level = "ERROR" and component = "payment"
| stats count() as errors, avg(latencyMs) as avgLatency by bin(5m)
| sort @timestamp desc
| limit 50
text
filter @type = "REPORT"
| stats max(@maxMemoryUsed / 1024 / 1024) as maxMB, avg(@duration) as avgMs, count(*) as invocations by bin(1h)

JSON fields are auto-discovered; parse @message "user=* action=*" as user, action handles text. You pay per GB scanned, so narrow the time range and log groups. Save queries, add them to dashboards, and use query-based metric extraction only when needed.

Retention, cost and security

  • Set retention on every group (CloudFormation default is never expire). Use Infrequent Access class for cheaper ingestion of rarely queried logs.
  • Data protection policies detect and mask PII (credit cards, emails) and report findings.
  • Encrypt with KMS (the key policy must allow the logs service); restrict access with IAM and resource policies; use VPC endpoints for private ingestion.
  • Control cost: reduce verbosity, sample debug logs, ship to S3 for long-term, and avoid high-cardinality metric filters.

Troubleshooting

No logs from EC2 usually means the agent is not running, the role lacks logs:CreateLogStream/PutLogEvents, or no network path to the endpoint. Lambda missing logs means the execution role lacks the logs permissions.

Logs Insights, metric filters and cost control

text
fields @timestamp, @message, requestId
| filter @message like /ERROR/
| stats count() as errors by bin(5m)
| sort errors desc
| limit 20
  • Metric filters turn matching log patterns into metrics (alarmable); they apply only to events ingested after creation.
  • Subscription filters stream events in near real time to Kinesis, Firehose or Lambda (up to two per log group); cross-account delivery uses a destination resource policy.
  • Embedded Metric Format (EMF) lets code emit metrics inside structured logs with no PutMetricData calls.
  • Log classes: Standard versus Infrequent Access (cheaper, fewer features). Set retention on every group, because the default is never expire.
  • Data protection policies mask sensitive data such as card numbers, and KMS encrypts log groups.
  • Use Live Tail to watch events as they arrive, and export tasks or subscriptions for archival to S3.

Real World Example

Scenario: a SaaS provider with 60 accounts needs central security logging. Each account's application and VPC Flow Logs are streamed by subscription filters to a CloudWatch Logs destination in a logging account, which feeds a Kinesis stream and Firehose that deliver compressed Parquet to S3 and indexed data to OpenSearch.

A metric filter on CloudTrail logs counts root logins and raises an alarm to the security channel. Engineers troubleshoot using Logs Insights across a selection of log groups in the monitoring account via cross-account observability, without needing access to production accounts.

Architecture Diagram

Log pipeline from application to analysis
Architecture
AWS Cloud
App + agent
Log groupretention + KMS
Metric filter-> alarm
Subscription filter-> Kinesis / Firehose
Logs Insightsad hoc queries

Logs are filtered into metrics and streamed to central storage.

  1. 1The agent or service writes events to a log stream in a log group.
  2. 2Retention and KMS encryption are applied at the group.
  3. 3A metric filter counts matching errors and an alarm notifies on-call.
  4. 4A subscription filter streams all events to Kinesis or Firehose for central storage.
  5. 5Engineers query recent data with Logs Insights.

Best Practices

  • ✓Set retention on every log group and use the Infrequent Access class where suitable.
  • ✓Emit structured JSON logs so metric filters and Insights queries are simple.
  • ✓Stream to central accounts with subscription filters or OAM, and enforce with Organization conditions.
  • ✓Use data protection policies and KMS to protect sensitive data.
  • ✓Limit Insights queries by time range and log groups to control cost.

Common Interview Questions

Exam Tips

DOP-C02 focus

  • "Near-real-time log delivery to S3/OpenSearch" = subscription filter to Firehose; export tasks are batch.
  • "Alarm on a log pattern" = metric filter + alarm.
  • "Query across logs interactively" = Logs Insights; "SQL on S3 logs" = Athena.
  • Cross-account log aggregation = Logs destination + subscription filter, or OAM.

Finished this lesson?

0 of 44 lessons done · 0% of the course