如何合并两条CloudWatch Logs Insights查询以单语句计算每小时请求错误率
实现方案
核心是利用CloudWatch Logs Insights的count_distinct_if条件聚合函数,无需分两次查询,单条语句就可以同时计算三个指标:
fields @timestamp, @message # 先过滤出所有MyAPI的返回日志,覆盖正常和异常场景 | filter @message like /reply.*MyAPI/ | parse @message '"reqID":*' as reqID # 分别聚合统计总请求、错误请求,再计算错误率,保留三位小数 | stats count_distinct(reqID) as total_requests, count_distinct_if(reqID, @message like /Exception/) as error_requests, round((count_distinct_if(reqID, @message like /Exception/) * 100.0 / count_distinct(reqID)), 3) as error_rate_percent by bin(1h) as hour # 按时间升序排序方便查看 | sort hour asc
语句说明
- 第一层过滤只保留
reply.*MyAPI的所有日志,避免重复扫描两次日志数据,查询效率更高 count_distinct_if(字段, 条件)是CloudWatch Logs Insights原生支持的条件聚合函数,只会统计符合指定条件的记录的去重计数值- 计算错误率的时候乘以
100.0是为了做浮点数除法,避免整数除法导致结果为0的问题,round函数可以按需调整保留的小数位数 - 如果需要调整时间分桶,直接修改
bin(1h)的参数即可,比如bin(30m)就是30分钟分桶
内容的提问来源于stack exchange,提问作者sak18
相关产品推荐
相关产品推荐

