如何基于AWS CloudWatch为每个摄像头创建离线超时告警?
问题描述
我的日志文件包含多个摄像头的消息,某摄像头离线后恢复上线的日志片段如下:
2024-11-15 13:10:11.234+00:00 [ 167] WARNING - bdab-b307-4df3-8596 CameraDecoder (testc00013.test0001ev) - Camera 1 Device communication error (NoDataException). Error: GetMediaDataBlock returned no data.
2024-11-15 13:10:18.602+00:00 [ 167] INFO - bdab-b307-4df3-8596 CameraDecoder (testc00013.test0001ev) - Camera 1 Device communication established
其中唯一摄像头ID为testc00013.test0001ev,离线标识为Device communication error,上线标识为Device communication established。需求是为每个摄像头创建告警:当摄像头离线后5分钟内未恢复上线时触发。尝试过Log Insights和指标过滤器,但不清楚如何针对每个唯一摄像头ID实现该需求。
操作步骤
1. 编写Log Insights查询提取关键字段
先通过查询解析日志,提取摄像头ID、事件类型和时间戳,为后续状态追踪做准备:
fields @timestamp, @message | parse @message "* - * CameraDecoder (*) - * *" as log_level, trace_id, camera_id, camera_name, event_msg | filter event_msg in ("Device communication error", "Device communication established") | extend event_type = case(event_msg == "Device communication error", "offline", "online") | sort camera_id, @timestamp desc
2. 按摄像头ID追踪离线持续时间
基于上面的查询,添加分组逻辑,判断每个摄像头离线是否超过5分钟:
fields @timestamp, @message | parse @message "* - * CameraDecoder (*) - * *" as log_level, trace_id, camera_id, camera_name, event_msg | filter event_msg in ("Device communication error", "Device communication established") | extend event_type = case(event_msg == "Device communication error", "offline", "online") | sort camera_id, @timestamp desc | partition by camera_id ( sort @timestamp desc | fill null(event_type) forward | extend time_since_offline = iff(event_type == "offline", now() - @timestamp, null) | filter time_since_offline > 300000 -- 300000毫秒=5分钟 | distinct camera_id )
这个查询会按摄像头ID分组,仅输出离线超过5分钟的设备ID。
3. 创建基于日志查询的告警
- 进入告警配置页,选择「基于日志查询的告警」类型
- 粘贴上面的最终查询语句,设置查询频率为1分钟(可根据需求调整)
- 配置触发条件:当查询结果返回的摄像头ID数量大于0时触发告警
- 在通知内容中添加摄像头ID变量,确保运维能直接定位问题设备
4. 验证告警逻辑
- 模拟某摄像头的离线日志且不发送上线日志,等待5分钟后检查是否触发告警
- 模拟离线后5分钟内发送上线日志,确认不会触发告警,验证逻辑正确性
内容的提问来源于stack exchange,提问作者AndyM

