Grafana中如何合并正则转换后同名标签并求和指标值?
Grafana路径标签合并求和解决方案
方法一:直接在PromQL中完成(推荐)
无需依赖Grafana转换,直接修改查询语句,一次性完成路径提取、分组求和,从根源避免重复标签问题。
使用regex_replace函数提取路径第一部分并生成新标签,再按新标签求和:
sum by(short_path) ( increase(http_request_duration_seconds_count{applikasjon="kundebetjening-web", path=~"/api-gateway/([^/]+)/.*",environment="prod"}[$__range]) | regex_replace(path, "/api-gateway/([^/]+)/.*", "/api-gateway/$1") as short_path )
或者用label_replace函数实现相同效果:
sum by(short_path) ( label_replace( increase(http_request_duration_seconds_count{applikasjon="kundebetjening-web", path=~"/api-gateway/([^/]+)/.*",environment="prod"}[$__range]), "short_path", "/api-gateway/$1", "path", "/api-gateway/([^/]+)/.*" ) )
方法二:通过Grafana转换功能实现
如果必须保留原查询,可通过两步转换完成合并求和:
- 提取字段转换:
- 选择「提取字段」转换类型,设置正则表达式为
/api-gateway/([^/]+)/.*,将捕获组1的内容映射为新字段(比如命名为short_path)。
- 选择「提取字段」转换类型,设置正则表达式为
- 分组求和转换:
- 添加「分组求和」转换类型,选择按
short_path字段分组,对指标数值(默认字段为Value)执行求和操作。
- 添加「分组求和」转换类型,选择按
这样就能将所有同名的short_path标签对应的指标值合并为总和,解决右侧图例重复的问题。
内容的提问来源于stack exchange,提问作者Tofik Sahraoui
相关产品推荐
相关产品推荐

