An application deployed on AWS Fargate publishes structured JSON logs to an Amazon CloudWatch Logs log group. Each log event contains fields such as `latency`, `statusCode`, `path`, and `userId`. A developer is tasked with creating a CloudWatch Logs Insights query to analyze application performance. The query must calculate the percentile of latency for all requests and count the number of server errors (where `statusCode` is or greater). The results must be grouped by the API `path` and aggregated into -minute intervals. Which CloudWatch Logs Insights query should the developer use to meet these requirements?
- Afields @timestamp, path, latency, statusCode | filter statusCode >= 500 | stats pct(latency, 95) as p95_latency, count() as error_count by path, bin(5m)
- Bfields @timestamp, path, latency, statusCode | stats pct(latency, 95) as p95_latency, count(statusCode >= 500) as error_count by path, bin(5m)
- fields @timestamp, path, latency, statusCode | stats pct(latency, 95) as p95_latency, sum(statusCode >= 500) as error_count by path, bin(5m)Answer
- Dfields @timestamp, path, latency, statusCode | stats pct(latency, 95) as p95_latency, count() filter(where statusCode >= 500) as error_count by path, bin(5m)
Answer
The query that uses the sum function with a conditional expression inside stats: 'fields @timestamp, path, latency, statusCode | stats pct(latency, 95) as p95_latency, sum(statusCode >= 500) as error_count by path, bin(5m)'
The correct query uses sum(statusCode >= 500) inside the stats command. In CloudWatch Logs Insights, boolean expressions inside aggregation functions evaluate to 1 for true and 0 for false. Therefore, summing the expression statusCode >= 500 effectively counts only the events where the status code indicates a server error, while allowing the percentile function pct(latency, 95) to be calculated over the entire dataset without prior filtering.
Step-by-Step Solution
Key Concept
Conditional aggregation in CloudWatch Logs Insights stats command
Estimated Time:1m 30s