如何通过AWS CloudWatch CLI聚合相同@timestamp的拆分@message日志?
AWS CloudWatch日志聚合同时间戳消息的实现方法
可以通过CloudWatch Logs Insights的查询语句实现同时间戳下日志消息的聚合,以下是两种常用方案:
1. 聚合为换行分隔的单字段
使用stats结合concat函数,将同一时间戳下的所有@message以换行符拼接成一个字段:
filter @message not like "GET / HTTP/1.1" | sort @timestamp asc | stats concat(@message, '\n') as combined_message by @timestamp
concat(@message, '\n'):把每条@message用换行符连接by @timestamp:按时间戳分组聚合
2. 聚合为消息列表(数组)
使用stats结合collect函数,将同一时间戳下的@message收集成一个数组字段:
filter @message not like "GET / HTTP/1.1" | sort @timestamp asc | stats collect(@message) as message_list by @timestamp
collect(@message):自动将同组的消息打包成数组,方便后续按列表形式查看
注意事项
如果日志的时间戳存在毫秒级差异(比如同一秒内的不同毫秒),导致无法正确聚合,可通过floor函数截断时间精度,比如统一按秒分组:
filter @message not like "GET / HTTP/1.1" | sort @timestamp asc | stats concat(@message, '\n') as combined_message by floor(@timestamp, 1s)
floor(@timestamp, 1s):将时间戳向下取整到最近的1秒,确保同一秒内的日志能被正确分组
内容的提问来源于stack exchange,提问作者Howins
相关产品推荐
相关产品推荐

