Storing and Querying Application Logs with CloudWatch Logs
This lesson explains how Amazon CloudWatch Logs stores, searches and analyses log data from AWS services and your applications.
Learning outcomes
After completing this lesson, you will be able to:
- Describe how log groups, log streams and retention settings organise log data.
- Choose between metric filters, CloudWatch Logs Insights, subscription filters and Live Tail for a question about logs.
- Identify the settings that control the cost of CloudWatch Logs.
Log groups and streams
Amazon CloudWatch Logs organises log data in two levels. A log group is a collection of logs that share the same settings, usually one per application, function or service; Lambda, for example, writes to a log group named /aws/lambda/<function-name> by default. A log group contains log streams, each a sequence of events from one source, such as one Lambda execution environment, one container or one EC2 instance. Settings are applied to the log group, so they cover every stream in it.
The most important setting is retention. By default, logs are kept forever, so storage charges grow every month for as long as the application runs. Setting a retention period, such as 30 days, deletes older events automatically. Log groups can also be encrypted with a customer managed AWS KMS key, and data protection policies can detect and mask sensitive data, such as email addresses or card numbers, in log events.
For long-term storage at lower cost, logs can be copied to Amazon S3, either with export tasks or continuously through a subscription filter to Amazon Data Firehose, and then queried with Amazon Athena when needed. Applications and AWS services need the logs:CreateLogGroup, logs:CreateLogStream and logs:PutLogEvents permissions to write logs; a Lambda function that produces no logs usually lacks them in its execution role.
Log groups and retention
Getting answers from logs
Logs become useful when they answer questions, and CloudWatch Logs provides a feature for each kind of question.
A metric filter watches a log group for a pattern, such as JSON events with level equal to ERROR, and turns each match into a metric value. An alarm on that metric then alerts on something that exists only in the logs. A metric filter applies only to events that arrive after it is created. Logs Insights runs interactive queries, with filtering, aggregation and sorting, across one or more log groups, for investigating a problem after the fact; it is charged by the amount of data scanned. Live Tail shows new log events as they arrive, optionally filtered, which is convenient while testing a deployment.
Log anomaly detection learns the usual patterns in a log group and highlights new or unusual ones, such as an error message that has never appeared before. Subscription filters stream matching events in near real time to a Lambda function, a Kinesis data stream or Amazon Data Firehose, for example to send logs from many accounts to a central logging account or to a third-party tool. The following table summarises the features.
| Feature | What it does |
|---|---|
| Metric filters | Turn matching log patterns into metrics you can alarm on, such as counting ERROR lines |
| Logs Insights | Runs interactive queries across log groups |
| Live Tail | Streams new log events in real time while you test or debug |
| Log anomaly detection | Highlights unusual patterns |
| Subscription filters | Stream log events in real time to Lambda, Kinesis Data Streams or Firehose, including to a central logging account |
Example. Count declined payments in JSON logs and set a 30-day retention. A metric filter counts only events that arrive after it is created.
aws logs put-metric-filter --log-group-name /aws/lambda/orders-api \
--filter-name payment-declined \
--filter-pattern '{ $.level = "ERROR" && $.errorType = "PaymentDeclined" }' \
--metric-transformations metricName=PaymentDeclined,metricNamespace=MyApp,metricValue=1,defaultValue=0
aws logs put-retention-policy --log-group-name /aws/lambda/orders-api --retention-in-days 30Which log feature?
A log bill that keeps growing
CloudWatch Logs costs have grown every month for a year. Investigation shows:
| Finding | Fix |
|---|---|
| Every log group has retention "Never expire" | Set retention: 30 days for debug logs, longer only where required |
| Functions log the full request body at INFO level | Log at INFO without bodies; DEBUG only when needed |
| Old logs needed for audits | Export to S3 or subscribe to Firehose, then lifecycle to Glacier |
Setting retention alone stops the growth. Structured JSON logs at the right level also make Logs Insights queries faster and cheaper, because they scan less data.
How can you raise an alarm when a log group records more than ten ERROR lines in five minutes?
Show answer
Create a metric filter that matches ERROR and publishes a metric, then a CloudWatch alarm on that metric with a threshold of 10 over a five-minute period.
Exam Tips
Remember for the exam
- To alarm on the number of errors in a log, create a metric filter and an alarm on it.
- If a Lambda function produces no logs, check that its execution role has CloudWatch Logs permissions.
- To watch logs in real time while testing, use CloudWatch Logs Live Tail.
- To archive logs cheaply, set a retention period and export older logs to S3.