如何在LogQL查询中同时unwrap多个标签?
LogQL多字段unwrap需求解答
可行性
完全可行。
具体操作方法
由于单条日志只会包含notifications_sent或notifications_delivered中的一个字段,直接同时对两个字段执行unwrap会导致部分条目因字段缺失报错,因此需要拆分处理后合并结果,以下是两种实用方法:
方法1:拆分独立查询合并结果
分别针对两个字段编写sum_over_time查询,用|运算符将结果合并:
sum_over_time({filename=~".+Notifications.+", log_level="INFO"} |~ "SentNotifications" | regexp "message=\"SentNotifications\", NotificationCount=\"(?P<notifications_sent>\\d+)\"" | unwrap notifications_sent [5m]) | sum_over_time({filename=~".+Notifications.+", log_level="INFO"} |~ "DeliveredNotifications" | regexp "message=\"DeliveredNotifications\", NotificationCount=\"(?P<notifications_delivered>\\d+)\"" | unwrap notifications_delivered [5m])
方法2:统一字段名后聚合(更简洁)
通过正则将两个通知计数统一映射到同一个字段(比如count),同时提取通知类型标签,再执行unwrap和聚合:
sum_over_time( {filename=~".+Notifications.+", log_level="INFO"} |~ "(SentNotifications|DeliveredNotifications)" | regexp "message=\"(?P<type>SentNotifications|DeliveredNotifications)\", NotificationCount=\"(?P<count>\\d+)\"" | unwrap count [5m] ) by (type, filename, log_level)
这种方法避免了重复的查询逻辑,聚合后能通过type标签清晰区分发送和送达的统计数据。
注:原查询中
filename=~"+.Notifications.+"的正则存在语法错误,修正为.+Notifications.+才能正确匹配包含Notifications的文件名。
内容的提问来源于stack exchange,提问作者John Grieb
相关产品推荐
相关产品推荐

