Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
637 views
in Technique[技术] by (71.8m points)

java - How to make own metrics in Spring Boot for prometheus

@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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

enter image description here enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...