Searching Logs with CloudWatch Logs Insights
During an incident, engineers need to search and aggregate logs quickly across many log groups. CloudWatch Logs Insights provides an interactive query language over CloudWatch Logs without any infrastructure. This lesson explains the query commands, parsing unstructured logs, aggregating with stats, querying many log groups and accounts, and features such as saved queries, query generation and field indexes.
Learning outcomes
After completing this lesson, you will be able to:
- Write Logs Insights queries using fields, filter, stats, sort, limit, parse and dedup.
- Explain how discovered fields and parse extract data from structured and unstructured logs.
- Describe querying across log groups and accounts and adding query results to dashboards.
- Explain cost and performance considerations, including field indexes and query scope.
- Explain how queries run programmatically and when to use period comparison, Live Tail or a metric filter instead.
The Query Language
A Logs Insights query is a pipeline of commands separated by the pipe character. The main commands are described below.
| Command | Purpose |
|---|---|
| fields | Select fields to display, and create computed fields |
| filter | Keep events matching conditions, with comparison operators, like, regular expressions and in |
| stats | Aggregate with count, sum, avg, min, max, pct (percentiles), count_distinct, grouped by fields or bin(time) |
| sort and limit | Order results and limit their number |
| parse | Extract fields from text with glob patterns or regular expressions |
| dedup | Remove duplicate results by fields |
| pattern | Group events into recurring patterns |
| display | Choose which fields appear in results |
Logs Insights automatically discovers fields in JSON logs and in logs from AWS services such as Lambda (@duration, @billedDuration, @maxMemoryUsed), VPC Flow Logs and CloudTrail. Every event also has system fields: @timestamp, @message, @logStream and @log.
Logs Insights commands
Examples
The following queries show typical operational uses.
# The 20 most recent errors with their request IDs
fields @timestamp, @message, requestId
| filter level = "ERROR"
| sort @timestamp desc
| limit 20
# p50, p90 and p99 Lambda duration in five-minute bins
filter @type = "REPORT"
| stats pct(@duration, 50) as p50, pct(@duration, 90) as p90, pct(@duration, 99) as p99 by bin(5m)
# Parse an unstructured line: "user=alice action=login result=failure ip=203.0.113.7"
parse @message "user=* action=* result=* ip=*" as user, action, result, ip
| filter action = "login" and result = "failure"
| stats count(*) as failures by user, ip
| sort failures desc
# Rejected traffic in VPC Flow Logs by source address
filter action = "REJECT"
| stats count(*) as rejected by srcAddr
| sort rejected desc
| limit 10Scope, Cost and Performance
Queries can run against many log groups at once, selected by name, prefix or a log group selection, and against log groups in linked source accounts when cross-account observability is configured. Queries are charged by the amount of data scanned, so narrowing the time range and the set of log groups reduces both cost and duration. Field indexes on frequently filtered fields, such as request ID or customer ID, let queries skip events that cannot match, which greatly speeds up and reduces the cost of needle-in-a-haystack searches. Queries time out after 60 minutes, and results are kept for seven days.
Logs Insights also accepts OpenSearch Piped Processing Language (PPL) and SQL for users familiar with them, can generate queries from natural language descriptions, and offers saved queries shared within the account. Query results can be added to CloudWatch dashboards as widgets that refresh automatically, and scheduled or programmatic queries run through the StartQuery and GetQueryResults APIs.
Running Queries Programmatically, Comparing Periods and Live Tail
Queries are asynchronous. StartQuery returns a query ID immediately, and the caller polls GetQueryResults until the status is Complete, Failed, Cancelled or Timeout. Times are given in seconds since the Unix epoch. This pattern lets automation use Logs Insights, for example a Lambda function that runs a query after an alarm fires and attaches the top error messages to the notification, or a CodeBuild step that checks a canary environment's logs for new errors before a pipeline promotes a release.
QUERY_ID=$(aws logs start-query \
--log-group-names /aws/lambda/checkout /aws/apigateway/checkout-access \
--start-time $(date -d '-30 minutes' +%s) --end-time $(date +%s) \
--query-string 'filter level = "ERROR" | stats count(*) as errors by errorCode | sort errors desc | limit 5' \
--query queryId --output text)
aws logs get-query-results --query-id "$QUERY_ID"Two console features help during investigations. The compare option runs the same query over the selected period and an equal earlier period, such as the same hour on the previous day, and shows the differences, which quickly separates new error types from errors that are always present. Live Tail streams matching log events from one or more log groups as they arrive, with filter terms and highlighting, which suits watching a deployment or reproducing a fault in real time; it is also available with aws logs start-live-tail. Live Tail sessions are charged by the minute, so they should be closed when no longer needed.
Run Logs Insights
Logs Insights Compared with Other Log Analysis
Logs Insights is the first choice for interactive investigation of logs in CloudWatch Logs. Other tools fit other needs, compared below and explained further in the final lesson of this module.
Investigating a Latency Incident
Customers report slow checkouts starting at 14:10. Logs from the API (API Gateway access logs), the checkout Lambda function and the payment service (JSON) are in separate log groups.
-
Confirm and size
Query the API access log group for p99 latency by bin(1m) between 13:30 and 15:00 to see when latency rose and by how much.
-
Locate
Query the Lambda log group's REPORT lines for duration percentiles and initialisation durations to see whether cold starts or execution time increased.
-
Find the cause
Query the payment service's logs across both log groups for errors with stats count by error code and dependency, revealing timeouts to a third-party provider beginning at 14:08.
-
Share
Save the queries and add the latency query to the service dashboard.
A Logs Insights query over 30 days of logs from 40 log groups is slow and expensive. How can it be improved?
Show answer
Narrow the time range and log groups to those relevant, filter early on indexed fields (creating field indexes for frequently searched fields), and aggregate rather than return raw events.
Exam Tips
Remember for the exam
- Logs Insights commands: fields, filter, stats (count, avg, pct, by bin()), sort, limit, parse, dedup, pattern.
- Fields are discovered automatically in JSON and AWS service logs; parse extracts fields from text.
- Queries span log groups and linked accounts; cost depends on data scanned, so narrow time ranges and use field indexes.
- Query results can be added to dashboards; queries can be generated from natural language.
- StartQuery is asynchronous (poll GetQueryResults); Live Tail streams events in real time; metric filters turn log patterns into metrics for alarms.