Sub topic 8
Log groups, log streams, and retention
This chapter assumes you can run AWS CLI commands, know what an IAM permission is, and have seen the CloudWatch metrics chapters. It covers how CloudWatch Logs stores log data and how to control how long that data lives. The agent, metric filters, and Logs Insights come in later chapters.
The three-level model
CloudWatch Logs organizes data in three levels:
- A log event is one record: a timestamp (in milliseconds since the Unix epoch) and a message string.
- A log stream is an ordered sequence of events from one source, such as one EC2 instance, one container, or one Lambda execution environment.
- A log group is a collection of streams that share settings: retention, encryption, access permissions, and metric filters.
Settings belong to the group, not the stream. You cannot give one stream a shorter retention than its siblings. If two sources need different retention, put them in different groups.
Naming
A common convention is a path-like group name per application or service, such as /app/web or /aws/lambda/checkout. Group names are 1 to 512 characters and may contain letters, digits, and _ - / . #. Stream names may not contain : or *. AWS services reserve prefixes such as /aws/lambda/, and they create groups there on your behalf.
A good stream name identifies the source, for example {instance_id} as in the agent configuration shown earlier in this tutorial. Names like stream1 make debugging harder later.
Creating groups and streams
Most AWS services and the CloudWatch agent create groups and streams automatically. You can also create them yourself:
aws logs create-log-group \
--log-group-name /app/web \
--log-group-class STANDARD
aws logs create-log-stream \
--log-group-name /app/web \
--log-stream-name manual-testThe log group class is chosen at creation and cannot be changed afterward. STANDARD supports all features. INFREQUENT_ACCESS costs less to ingest but supports fewer features (it has no metric filters, for example), so choose it only for logs you rarely query.
Writing and reading events
You will normally let an agent or SDK write events. Writing one by hand shows the data model:
aws logs put-log-events \
--log-group-name /app/web \
--log-stream-name manual-test \
--log-events timestamp=$(date +%s%3N),message="ERROR test event"date +%s%3N produces milliseconds on GNU date. On macOS, use a different method, because the BSD date does not support %N.
Read the events back with aws logs tail, which can also follow new events:
aws logs tail /app/web --since 15m --followWrites have limits that cause most put-log-events errors:
- A batch holds at most 10,000 events and about 1 MiB.
- Events in a batch must be in chronological order.
- A batch cannot span more than 24 hours.
- An event cannot be older than 14 days or more than 2 hours in the future, and it cannot be older than the group's retention period.
Events rejected for timestamp reasons are reported in the response as rejectedLogEventsInfo. The call itself can still succeed, so check that field if events seem to be missing.
Retention
By default a new log group has Never expire retention. Data accumulates forever, and you pay storage for all of it. For many services this is the main source of unnoticed CloudWatch cost.
Set retention on the group:
aws logs put-retention-policy \
--log-group-name /app/web \
--retention-in-days 30Retention accepts only specific values: 1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1096, 1827, 2192, 2557, 2922, 3288, or 3653 days. Any other number returns an InvalidParameterException. To return to keeping data forever, run delete-retention-policy.
Retention is measured from each event's timestamp, not from when the stream or group was created. Expiry is also not instant. CloudWatch typically deletes expired events within about 72 hours, so storage can still show data slightly past the limit.
Inspecting groups
List groups with their retention and stored size to find the expensive ones:
aws logs describe-log-groups \
--query 'logGroups[].{name:logGroupName,days:retentionInDays,bytes:storedBytes}' \
--output tableA group with a blank days value has no retention policy. Streams in one group are listed with describe-log-streams. Use --order-by LastEventTime --descending to see the most recently active ones first:
aws logs describe-log-streams \
--log-group-name /app/web \
--order-by LastEventTime \
--descending \
--max-items 5Encryption and access
All log data is encrypted at rest. To use your own AWS KMS key, associate it with the group using associate-kms-key. The key policy must allow the CloudWatch Logs service principal for your region to use it. Without that, writes fail.
Access is controlled with IAM. Permissions can be scoped to a group ARN, which is another reason to keep one group per application. Writers need logs:CreateLogStream and logs:PutLogEvents. Add logs:CreateLogGroup only if the writer should create groups itself.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| Storage and cost grow without limit | Groups left at Never expire, often created automatically by Lambda | Set retention on each group, or create the group yourself in infrastructure code with a retention value |
| `ResourceNotFoundException` on write | The group or stream does not exist | Create it first, or grant create permissions |
| Events accepted but not visible | Timestamps outside the allowed window | Check `rejectedLogEventsInfo` and the clock on the source |
| Retention call fails | Unsupported number of days | Use one of the listed values |
| Hard to find an instance's logs | Generic stream names | Name streams after the instance or container ID |
Exercise
A Lambda function's log group was created automatically two years ago and now holds 900 GB. You set --retention-in-days 30 today. Will storage drop immediately, and what happens to the older events?
Show answer
Storage will not drop immediately. Events older than 30 days become eligible for deletion and are permanently removed, typically within about 72 hours. If you need them, export them to S3 before setting the policy.
Exercise
You want application logs kept 14 days and audit logs kept 365 days, both from the same EC2 instance. How should you organize them?
Show answer
Use two log groups, for example /app/web with 14-day retention and /app/audit with 365-day retention. Retention is a group setting, so one group cannot hold both policies. The instance can write one stream to each group.