且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Spring Boot 中为 prometheus 创建自己的指标

更新时间:2023-01-18 18:30:00

您可以使用

@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' ]