如何在 Spring Boot 中为 prometheus 创建自己的指标 [英] How to make own metrics in Spring Boot for prometheus

查看:66
本文介绍了如何在 Spring Boot 中为 prometheus 创建自己的指标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@GetMapping(value = "/ownMetrics")公共字符串 ownMetrics() {return "ownmetrics_age{Name=\"Age\",} ";+ 年龄;}

我想制作自己的指标,并以正确的格式制作普罗米修斯可以读取的格式.

解决方案

您可以使用

@GetMapping(value = "/ownMetrics")
public String ownMetrics() {
     return "ownmetrics_age{Name=\"Age\",} " + age;
}

I want to make my own metrics and in right format that prometheus it can read.

解决方案

You can use Micrometer for custom metrics and expose it to prometheus. If you are using gradle add these dependencies:

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-webflux'

    // metrics: micrometer + prometheus
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    implementation 'io.micrometer:micrometer-registry-prometheus:1.6.6'
}

At your service class add a MeterRegistry and a Counter. Initiate the Counter and call the incrementer of this counter. In my example is the bidderCallsCounter.increment();. I defined the metric name to be bidder.calls and Prometheus will replace the . by _.

@Slf4j
@Service
public class YourService {
    private MeterRegistry meterRegistry;
    private Counter bidderCallsCounter;
    public YourService(MeterRegistry meterRegistry) {
        this.meterRegistry = meterRegistry;
    }
    private void initBidderCallCounter() {
        // CREATE A COUNTER
        bidderCallsCounter = this.meterRegistry.counter("bidder.calls", "type", "bidder");
    }
    private Stream<Flux<BidResponse>> bidResponseStreamMono(Mono<BidRequest> bidRequestMono) {
        return biddersWebClient.stream()
                .map(bidderWebClient -> {
                    // THE INCREMENTER
                    bidderCallsCounter.increment();
                    return bidderWebClient.post()
                            ....
                            .log("BidResponse: ");
                });
    }
}

Then after you configure your Prometheus target, access the http://172.17.0.1:8080/actuator/prometheus that you can see the custom metrics available. On the screenshot you can see that Prometheus scrapes the metric bidder_calls.

scrape_configs:
  - job_name: 'spring-actuator'
    metrics_path: '/actuator/prometheus'
    scrape_interval: 5s
    static_configs:
      # this should be the target host IP which is outside of the docker:
      # 172.17.0.1   or   "export DOCKER_GATEWAY_HOST=$(hostname -I | awk '{print $1}')"
      - targets: [ '172.17.0.1:8080' ]

这篇关于如何在 Spring Boot 中为 prometheus 创建自己的指标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆