0Pricing
AWS Solutions Architect · Lesson

CloudWatch Logs and Log Insights

Aggregate logs from EC2, Lambda, and containers into log groups, and run CloudWatch Logs Insights queries to find errors and patterns.

CloudWatch Logs and Log Insights is a free AWS Solutions Architect lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AWS Solutions Architect learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

CloudWatch Logs Overview

Amazon CloudWatch Logs is a fully managed log aggregation service that collects, stores, and analyses log data from AWS services and your own applications. Unlike traditional log management where you SSH into servers to read files, CloudWatch Logs centralises all logs in a durable, encrypted store with built-in querying, filtering, metric extraction, and retention management. It integrates natively with EC2, Lambda, ECS, EKS, API Gateway, CloudTrail, and VPC Flow Logs.

Log Groups and Log Streams

Logs are organised hierarchically: a log group is a named container for logs that share the same retention and access control settings (for example, /aws/lambda/my-function). Within a log group, each log stream represents a single source of sequential log events — one EC2 instance, one Lambda container, or one ECS task. A log group can have thousands of streams, but each stream belongs to exactly one log group.

# Create a log group with 30-day retention
aws logs create-log-group \
  --log-group-name /myapp/production/api

aws logs put-retention-policy \
  --log-group-name /myapp/production/api \
  --retention-in-days 30

# List log streams in a group
aws logs describe-log-streams \
  --log-group-name /myapp/production/api \
  --order-by LastEventTime \
  --descending

Sending Logs from Lambda and EC2

AWS Lambda automatically sends all stdout and stderr output to CloudWatch Logs — you just need the Lambda execution role to include logs:CreateLogGroup, logs:CreateLogStream, and logs:PutLogEvents. For EC2 instances, you install the CloudWatch Agent and configure which log files to tail (for example, /var/log/nginx/access.log), what log group to write to, and what pattern identifies individual log entries.

# CloudWatch Agent config for tailing an application log file
# /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.json
# {
#   "logs": {
#     "logs_collected": {
#       "files": {
#         "collect_list": [{
#           "file_path": "/var/log/myapp/app.log",
#           "log_group_name": "/myapp/production/api",
#           "log_stream_name": "{instance_id}",
#           "timestamp_format": "%Y-%m-%dT%H:%M:%S"
#         }]
#       }
#     }
#   }
# }

CloudWatch Logs Insights

CloudWatch Logs Insights is an interactive query engine that lets you search and analyse log data using a purpose-built query language. You can run queries across one or more log groups, filter by time range, extract fields from structured or unstructured log lines, aggregate data, and visualise results as bar charts or time series. Queries run on demand and are charged per GB of data scanned — structuring logs as JSON reduces scan volume significantly.

# Find the top 10 slowest Lambda invocations in the last hour
aws logs start-query \
  --log-group-name /aws/lambda/my-function \
  --start-time $(date -d '1 hour ago' +%s) \
  --end-time $(date +%s) \
  --query-string 'filter @type = "REPORT"
| fields @requestId, @duration
| sort @duration desc
| limit 10'

Logs Insights Query Language

The Logs Insights query language uses pipe-separated commands: fields selects which fields to display, filter narrows events (supports regex with like and =~), stats aggregates data, sort orders results, and limit caps the number of results. The service automatically discovers fields in JSON-formatted log lines. For unstructured logs, you can parse values using parse with glob or regex patterns.

# Count errors by status code in the last 24 hours
fields @timestamp, @message
| filter @message like /ERROR/
| parse @message '* * * [*] "* *" * *' as host, user, datetime, request, method, status, bytes
| stats count(*) as errorCount by status
| sort errorCount desc
| limit 20

Metric Filters: Logs to Metrics

Metric filters continuously scan incoming log events for patterns and increment a custom CloudWatch metric each time a match is found. For example, you can create a metric filter on a Lambda log group that increments an ErrorCount metric every time a log line contains ERROR. You then create a CloudWatch alarm on this metric to alert your team. This converts your logs into actionable metrics without storing results in a separate database.

# Create a metric filter that counts ERROR lines
aws logs put-metric-filter \
  --log-group-name /myapp/production/api \
  --filter-name ErrorCount \
  --filter-pattern 'ERROR' \
  --metric-transformations \
    metricName=ApplicationErrors,metricNamespace=MyApp,metricValue=1,defaultValue=0

# Now create an alarm on the resulting metric
aws cloudwatch put-metric-alarm \
  --alarm-name HighErrorRate \
  --metric-name ApplicationErrors \
  --namespace MyApp \
  --statistic Sum \
  --period 60 \
  --evaluation-periods 1 \
  --threshold 10 \
  --comparison-operator GreaterThanThreshold \
  --alarm-actions arn:aws:sns:us-east-1:111122223333:Ops

Log Subscriptions and Streaming

A subscription filter streams log events in near real time to another service for processing or storage. You can stream to AWS Lambda (to transform and route logs), Amazon Kinesis Data Streams (for high-volume log processing), or Amazon Kinesis Firehose (to deliver to S3, OpenSearch, or Splunk). Each log group supports up to two subscription filters. Cross-account log streaming requires a destination with an appropriate resource policy.

# Stream all logs containing ERROR to a Kinesis Firehose for S3 archiving
aws logs put-subscription-filter \
  --log-group-name /myapp/production/api \
  --filter-name ErrorsToFirehose \
  --filter-pattern 'ERROR' \
  --destination-arn arn:aws:firehose:us-east-1:111122223333:deliverystream/LogArchive \
  --distribution 'ByLogStreamName'

Retention Policies and Cost Management

By default, CloudWatch Logs stores data indefinitely, which can become expensive. Set retention policies on every log group to automatically delete old log events. Common retention periods are 7 days for debugging logs, 30 days for application logs, and 1-5 years for audit logs. You can export log groups to S3 for long-term, low-cost archiving using the create-export-task API, though exports are batch operations (not real time).

# Set retention on all log groups that have no retention policy
aws logs describe-log-groups \
  --query 'logGroups[?!retentionInDays].logGroupName' \
  --output text | tr '\t' '\n' | while read lg; do
    aws logs put-retention-policy \
      --log-group-name "$lg" \
      --retention-in-days 90
    echo "Set 90-day retention on $lg"
done

VPC Flow Logs

VPC Flow Logs capture metadata about IP traffic flowing to and from network interfaces in your VPC, subnets, or individual ENIs. They are stored in CloudWatch Logs or S3. Flow logs include source IP, destination IP, port, protocol, packet count, byte count, action (ACCEPT or REJECT), and timestamp. They are invaluable for troubleshooting security group and NACL rules, detecting port scans, and auditing traffic patterns — but they do NOT capture actual packet payloads.

# Enable VPC Flow Logs to CloudWatch Logs
aws ec2 create-flow-logs \
  --resource-ids vpc-0abc1234def567890 \
  --resource-type VPC \
  --traffic-type ALL \
  --log-destination-type cloud-watch-logs \
  --log-group-name /aws/vpc/flow-logs \
  --deliver-logs-permission-arn arn:aws:iam::111122223333:role/FlowLogsRole

Querying VPC Flow Logs with Insights

CloudWatch Logs Insights is particularly powerful for VPC Flow Log analysis. You can quickly identify rejected traffic, find the top talkers by byte volume, detect unusual connections, or isolate traffic to a specific instance. The flow log format is space-separated by default, but publishing in JSON format to CloudWatch Logs makes field extraction automatic in Insights queries.

# Find top 10 source IPs by rejected byte volume in the last day
fields srcAddr, dstAddr, dstPort, action, bytes
| filter action = 'REJECT'
| stats sum(bytes) as rejectedBytes by srcAddr
| sort rejectedBytes desc
| limit 10

Log Encryption with KMS

CloudWatch Logs encrypts all data at rest by default using AWS-managed keys. For enhanced security — particularly in regulated environments — you can associate a customer-managed KMS key with a log group. This gives you control over key rotation and access, and enables you to revoke access to all log data by disabling the key. The KMS key must have a key policy that grants CloudWatch Logs permission to use it for encryption and decryption.

# Associate a KMS key with a log group
aws logs associate-kms-key \
  --log-group-name /myapp/production/api \
  --kms-key-id arn:aws:kms:us-east-1:111122223333:key/KEY_ID

# Verify encryption is configured
aws logs describe-log-groups \
  --log-group-name-prefix /myapp/production \
  --query 'logGroups[].{Name:logGroupName,KmsKey:kmsKeyId}'

Quick Check

Test your understanding of AWS Solutions Architect (SAA-C03) concepts from this lesson.

Lesson Recap

In this lesson you learned: log groups and streams organise logs by source with configurable retention, Logs Insights lets you query and aggregate log data with a powerful pipe-based query language, and metric filters convert log patterns into CloudWatch metrics that can trigger alarms. Next up we explore CloudWatch Dashboards and Container Insights for operational visibility.

Frequently asked questions

Is the “CloudWatch Logs and Log Insights” lesson free?

Yes — the full text of “CloudWatch Logs and Log Insights” is free to read here on the web, and the AWS Solutions Architect course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AWS Solutions Architect course, upgrade to CoddyKit PRO.

What will I learn in “CloudWatch Logs and Log Insights”?

Aggregate logs from EC2, Lambda, and containers into log groups, and run CloudWatch Logs Insights queries to find errors and patterns. You practise AWS Solutions Architect with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start AWS Solutions Architect?

No prior experience is required. AWS Solutions Architect on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “CloudWatch Logs and Log Insights” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this AWS Solutions Architect lesson?

Yes. Every AWS Solutions Architect lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. CloudWatch Metrics, Namespaces, and Dimensions
  2. CloudWatch Alarms and Composite Alarms
  3. CloudWatch Logs and Log Insights
  4. CloudWatch Dashboards and Container Insights
← Back to AWS Solutions Architect