Sub topic 11
Querying logs with Logs Insights
This chapter assumes you know what a log group and log stream are, can run AWS CLI commands, and have IAM permission to read logs (logs:StartQuery, logs:GetQueryResults, logs:DescribeLogGroups). It covers the Logs Insights query model, the commands you will use most, how to run queries from the CLI, and the errors that trip people up.
What Logs Insights does
CloudWatch Logs Insights is an interactive query engine for log data stored in CloudWatch Logs. You choose one or more log groups and a time range, then write a query. Insights scans the matching log events and returns rows or aggregated statistics.
Use it when you need to ask a question about past events, such as "which errors happened most often in the last hour?" A metric filter, covered in the previous chapter, answers a different need. It counts matching events as they arrive and produces a metric you can alarm on. Insights runs on demand over stored data and does not produce a metric by itself.
| Need | Tool |
|---|---|
| Alarm when errors exceed a threshold | Metric filter plus alarm |
| Investigate which errors occurred and why | Logs Insights |
| Show a recurring count on a dashboard | Either, depending on whether you need a metric |
The query model
A query is a sequence of commands joined by the pipe character |. Each command receives the rows produced by the previous one. The first command usually selects fields. Later commands filter, aggregate, sort, and trim.
The query below is the one from this tutorial's reference material.
fields @timestamp, @message
| filter @message like /ERROR/
| stats count() as errors by bin(5m)
| sort errors desc
| limit 20Read it from top to bottom:
fieldspicks the columns to carry forward.filterkeeps only events whose message matches the regular expression/ERROR/.statsgroups the remaining events into 5-minute bins and counts each bin.sortorders the bins by count, highest first.limitkeeps the top 20 rows.
System fields
Every log event has fields that Insights adds automatically. They start with @.
| Field | Meaning |
|---|---|
| `@timestamp` | The event time |
| `@message` | The raw log line |
| `@logStream` | The stream the event came from |
| `@log` | The account ID and log group name |
| `@ingestionTime` | When CloudWatch received the event |
If a log event is valid JSON, Insights extracts its keys as fields automatically. A line such as {"level":"ERROR","path":"/cart","latency":412} gives you fields named level, path, and latency. Nested keys use dot notation, for example request.path. For plain-text logs, you extract fields yourself with parse.
The commands you will use most
filter
filter keeps rows that satisfy a condition. You can combine conditions with and, or, and not.
fields @timestamp, level, path, latency
| filter level = "ERROR" and latency > 500Common operators are =, !=, <, >, like (substring or regular expression), in, and ispresent(field).
parse
parse extracts values from unstructured text into new fields. You can use a glob pattern with * wildcards, or a regular expression with named capture groups.
fields @timestamp, @message
| parse @message "user=* action=* duration=*ms" as user, action, duration
| filter action = "checkout"
| stats avg(duration) as avg_ms, max(duration) as max_ms by user
| sort avg_ms descExtracted values are strings at first. Insights converts them when you use them in numeric functions such as avg, but comparisons are safer when you know the field really holds numbers.
stats
stats aggregates rows. Useful functions include count(), count_distinct(), sum(), avg(), min(), max(), and pct(field, 95) for percentiles. You can group with by on one or more fields, and bin(period) turns timestamps into time buckets.
fields @timestamp, latency
| stats count() as requests, pct(latency, 95) as p95 by bin(1m)Without bin(), stats returns a table. With bin(), the result can be drawn as a time series, which matters for dashboards.
sort, limit, and display
sort takes asc or desc. limit caps the number of rows returned. display chooses which fields appear in the final output, which is useful when earlier steps created helper fields.
Running a query from the CLI
The console is convenient for exploration. The CLI is better for scripts. Running a query takes two calls, because queries run asynchronously: you start the query and then fetch its results.
QUERY_ID=$(aws logs start-query \
--log-group-name /app/web \
--start-time "$(date -u -d '1 hour ago' +%s)" \
--end-time "$(date -u +%s)" \
--query-string 'fields @timestamp, @message | filter @message like /ERROR/ | stats count() as errors by bin(5m) | sort errors desc | limit 20' \
--query queryId \
--output text)
sleep 5
aws logs get-query-results --query-id "$QUERY_ID"Notes on this example:
--start-timeand--end-timeare Unix epoch seconds. Thedate -dsyntax shown works with GNU date on Linux. On macOS, usedate -u -v-1H +%s.- The
--query queryIdargument is the CLI's own JMESPath option, and it is unrelated to the Insights query string. - The response contains a
statusofScheduled,Running,Complete,Failed,Cancelled, orTimeout. Poll until it isCompletebefore trusting theresultsarray. - The response also contains
statisticswithrecordsScannedandbytesScanned. Check these when you want to understand a query's cost.
To query several log groups at once, pass --log-group-names with a list instead of --log-group-name. The @log field then tells you which group each row came from.
Cost and performance
Insights charges by the amount of data scanned. Two habits keep this low:
- Narrow the time range. A query over 15 minutes scans far less than one over 30 days.
- Select only the log groups you need.
Put filter as early as possible so later commands handle fewer rows. Also remember that retention affects what you can query: events that expired under the log group's retention setting are gone.
Common errors
| Symptom | Likely cause |
|---|---|
| Zero results | The time range does not cover the events, or the log group name is wrong |
| `MalformedQueryException` | A typo in a command, a missing pipe, or unbalanced quotes or slashes |
| Fields show as empty | Log lines are not JSON and no `parse` step extracts them |
| Results cut off at 10,000 rows | Insights returns at most 10,000 rows per query. The default `limit` is 1,000 in the console, so set `limit` explicitly |
| Query status `Timeout` | The query ran longer than 60 minutes. Narrow the time range or groups |
| `AccessDeniedException` | Missing `logs:StartQuery` or `logs:GetQueryResults`, or no read access to a target group |
| Case mismatch in `like` | `like` is case sensitive. Use `/(?i)error/` for case-insensitive matching |
From query to dashboard
A query that ends in stats ... by bin(...) can be added to a dashboard as a log widget. The widget reruns the query each time the dashboard loads, so it also scans data each time. For counts you need frequently or want to alarm on, a metric filter is cheaper and can trigger alarms. Use Insights widgets for investigation views that people open occasionally.
Exercise
Your application writes plain-text lines such as 2026-11-26T18:02:11Z order=8841 status=500 duration=1290ms. Write a Logs Insights query that finds the 10 slowest requests with status 500 in the last hour's selected range.
Show answer
fields @timestamp, @message
| parse @message "order= status= duration=*ms" as order, status, duration
| filter status = "500"
| sort duration desc
| limit 10
The parse step extracts three fields from the text. The filter keeps only status 500 rows, and sort with limit returns the 10 longest durations. Set the one-hour range with the time picker or the --start-time and --end-time arguments.
Exercise
A query run through the CLI returns an empty results array and "status": "Running". What went wrong, and what should the script do?
Show answer
The script read the results before the query finished. Insights queries run asynchronously, so the script should call get-query-results repeatedly, with a short wait between calls, until status is Complete (and handle Failed, Cancelled, and Timeout as errors).