Chapter 95: Logging with Loki, Elastic Stack and CloudWatch
95.12 Logs Insights QL — fields, filter, stats and time scope
Story (fictional teaching scenario). At a fictional Chennai shop, Yuki from Osaka first queries a short incident window rather than scanning every group for a month.
Why
The same question can cost more and take longer when the scope is unnecessarily broad.
What
- Logs Insights QL is a CloudWatch query language; this lesson uses QL, not SQL or another supported interface.
fieldsselects fields,filterkeeps matching events, andstatsaggregates.- Aggregate means summarize many records into counts or other values.
@timestampis a service-provided discovered field; custom JSON fields may also be discovered.- A query scope includes log groups and time range, not just query text.
How
-
Select only the necessary groups and the narrowest useful time window.
-
Choose fields before investigating individual records.
-
Filter exact categories or numeric conditions.
-
Aggregate when you need a total; do not confuse result limits with a guaranteed scan-cost cap.
Example 1: Read selected error events
- Read the command or request.
fields @timestamp, service, level, request_id, latency_ms
| filter level = "ERROR"
| sort @timestamp asc
| limit 20
- Read the result.
Output (illustrative; NOT executed against Loki, Elastic or CloudWatch)
Illustrative fixture rows: req-demo-003 and req-demo-004.
- Line by line:
fieldslists output columns. The filter selects our synthetic severity.sortorders by the service timestamp.limit 20caps returned rows; it is not a universal promise of scanning only 20 events. No query, paid scan or AWS call was made.
Example 2: Aggregate counts
- Read the command or request.
filter level = "ERROR"
| stats count(*) as errors by service
- Read the result.
Output (illustrative; NOT executed against Loki, Elastic or CloudWatch)
service=bakery-api, errors=2
- Line by line: The filter keeps error records first.
count(*)counts those records.as errorsnames the result column.by servicegroups the count. This output assumes only the six fixture events in the chosen scope, not a real CloudWatch result.
Ravindra Bagale's Tip
Query scope is a cost and correctness decision.
Query scope हा cost आणि correctness दोन्हींचा निर्णय आहे.
Query scope cost और correctness दोनों का फैसला है.
Did you understand? Let us try it once more.