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

Spring Boot应用Prometheus指标生成问题:后缀与标签逗号异常

Prometheus Counter指标问题解决方案

问题1:计数器名称自动追加_total后缀

原因

Prometheus官方规范要求Counter类型指标的名称必须以_total结尾,用于明确标识这是一个单调递增的计数器。你使用的simpleclient库严格遵循该规范,会自动为Counter指标名称添加_total后缀。

解决办法

有两种可选方案:

  • 方案1:遵循Prometheus规范
    直接接受_total后缀,这是Prometheus生态的标准做法,能保证指标语义的一致性,避免后续工具解析出现问题。
  • 方案2:改用Gauge模拟计数器(不推荐)
    如果你必须自定义指标名称,可使用Gauge类型手动实现递增逻辑(但会丢失Counter的语义特性,比如PromQL的rate()函数对Gauge的兼容性不如Counter)。修改代码如下:
    public class PrometheusUtility {
    
        private PrometheusUtility(){
        }
        
        static CollectorRegistry registry = CollectorRegistry.defaultRegistry;  
        
        static final Gauge counter = Gauge.build().name("http_request").help("help").labelNames("method","status","api", "component").register(registry);
        static final Gauge dsCounter = Gauge.build().name("http_downstream_request").help("Records the downstream request count").labelNames("method","status","api", "component", "downstream").register(registry);    
        
        public static void incrementCounter(String method, String status, String apiName, String component){
            counter.labels(method,status,apiName,component).inc();      
        }
        
        public static void incrementDownstreamCounter(String method, String status, String apiName, String component, String downstream){
            dsCounter.labels(method,status,apiName,component, downstream).inc();        
        }   
        
    }
    

问题2:指标最后一个标签末尾多逗号

原因

这是simpleclient旧版本(0.16.0)存在的格式化bug,新版本已修复该问题。

解决办法

升级simpleclient_spring_boot依赖到0.17.0及以上版本,修改pom.xml:

<dependency>
    <groupId>io.prometheus</groupId>
    <artifactId>simpleclient_spring_boot</artifactId>
    <version>0.17.0</version> <!-- 或更高稳定版本 -->
</dependency>

升级后,指标输出的标签末尾将不再出现多余逗号,格式会变为:

http_request_total{method="Post",status="200",api="newMail",component="mx"} 1.0
http_downstream_request_total{method="Post",status="200",api="newMail",component="mx",downstream="mwi"} 1.0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 02:40:39