You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Grafana中按去参后的log_request分组计算avg_over_time

问题:Loki查询中按去除URL参数后的log_request分组计算响应时间平均值

日志示例

{
   "alpha" : 10,
   "log_response_time" : 0.23,
   "log_request" : "/core/login?abc=txt"
}

需求说明

部分log_request字段带有URL参数,部分没有。需要按**去除URL参数后的log_request**分组,计算log_response_time的avg_over_time。若不处理参数,结果集会出现超过500个唯一值导致查询失败,且将相似API分开统计无意义。

尝试过的查询及问题

使用以下查询语句时,分组仍基于原始的log_request字段,而非处理后的字段:

avg_over_time({container="/web", hostname="abc-prod"} | json | line_format `{{ __line__  | replace .log_request (regexReplaceAll "\\?.*$" .log_request "")  }}` | unwrap log_response_time [1m]) by (log_request)

已确认单独执行以下语句可正确去除URL参数,得到无参数的log_request:

{container="/web", hostname="abc-prod"} | json | line_format `{{ __line__  | replace .log_request (regexReplaceAll "\\?.*$" .log_request "")  }}`

解决方案

方法1:直接替换原log_request字段的值

使用regexReplaceAll直接修改log_request字段的内容,之后基于修改后的字段分组:

avg_over_time({container="/web", hostname="abc-prod"} | json | log_request = regexReplaceAll("\\?.*$", log_request, "") | unwrap log_response_time [1m]) by (log_request)

方法2:生成新的处理后字段

如果不想修改原始字段,可以生成一个新的字段(比如clean_log_request),然后基于这个新字段分组:

avg_over_time({container="/web", hostname="abc-prod"} | json | clean_log_request = regexReplaceAll("\\?.*$", log_request, "") | unwrap log_response_time [1m]) by (clean_log_request)

原理说明

之前使用line_format的方式仅会格式化输出的日志行内容,不会修改Loki提取出的字段值,因此后续的by (log_request)仍然引用原始的未处理字段。而上述两种方法通过字段赋值操作,直接更新或生成处理后的字段,确保分组逻辑基于清洗后的路径。

内容的提问来源于stack exchange,提问作者Ouroboros

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 18:27:09