如何在Grafana中按状态统计特定分支的测试运行总数?
问题描述
需要构建Grafana图表,展示特定分支下按状态划分的已完成测试运行数量。例如过去12小时内develop分支有12次运行通过、3次运行失败。
当前实现的TypeScript代码:
- 定义Gauge指标:
this.runStatusGauge = new Gauge({ name: 'test_run_status', help: 'Test run status', labelNames: ['runName', 'status'], registers: [this.register], });
- 设置指标值(始终为1,仅修改status标签):
this.runStatusGauge.set( { runName: this.runName, status: '<passed or failed>', }, 1, );
- 推送到Pushgateway:
await this.pushgateway.pushAdd({ jobName: this.jobName, groupings: { env: this.options.env, projectName: this.projectName || 'undefined project', branchName: this.branchName, }, });
Prometheus收到的指标示例:
test_run_status{ branchName="local-new", env="staging", exported_env="staging", exported_job="pw_metrics", instance="", job="external-pushgateway", project="", projectName="widget", runName="Local run name 5f99692c-32df-4d33-89f9-d2ddee90c1d9", service="", source="", status="failed" } 1
尝试构建饼图时,图表始终按状态显示独立值且均为1,无法正确展示各状态下的测试运行总数。
解决方案
1. 调整PromQL查询实现聚合统计
当前每个测试运行对应一条值为1的指标,需要通过聚合函数将同状态的指标求和:
sum(test_run_status{branchName="develop"}) by (status)
如果需要限定统计过去12小时的数据,结合时间范围使用sum_over_time:
sum_over_time(test_run_status{branchName="develop"}[12h]) by (status)
注意:Pushgateway会持久化指标,若未清理旧数据,上述查询会统计所有历史测试运行。
2. 优化指标类型(推荐方案)
使用Counter类型替代Gauge,更符合Prometheus统计计数的规范:
- 修改TypeScript代码定义Counter指标:
this.runStatusCounter = new Counter({ name: 'test_run_status_total', help: 'Total number of test runs by status', labelNames: ['status', 'branchName', 'projectName', 'env'], registers: [this.register], }); // 测试运行完成时递增对应状态的计数器 this.runStatusCounter.inc({ status: '<passed or failed>', branchName: this.branchName, projectName: this.projectName || 'undefined project', env: this.options.env, });
- 用PromQL查询过去12小时的运行次数增量:
increase(test_run_status_total{branchName="develop"}[12h]) by (status)
3. Grafana饼图配置
- 选择饼图面板,将上述PromQL作为数据源查询
- 在面板设置中,将图例字段设为
status,值字段使用聚合后的求和/增量结果 - 可添加分支、环境等变量,方便切换查看不同维度的数据
内容的提问来源于stack exchange,提问作者Captain Sparrow
相关产品推荐
相关产品推荐

