springkotlinreactive-programmingprometheusspring-webclient

How to expose webClient metrics in prometheus?


I want to expose the metrics of a WebClient call to a downstream system from the service, metrics like count of request, min, max time for the response is needed.

I want to know how I can write a gauge for a reactive webclient.

Here is a sample MeterBinder that I'm interested to use with webclient.

class Metrics : MeterBinder {
    override fun bindTo(registry: MeterRegistry) {
        Gauge.builder("metrics", Supplier { Math.random() })
                .baseUnit("status")
                .register(registry)
    }
}

Solution

  • If you want to get the metrics of the WebClient call you can use ExchangeFilterFunction which is used as an interceptor. By default, there is one implementation of ExchangeFilterFunction i.e MetricsWebClientFilterFunction which can be added as a filter with your WebClient to give metrics like Number of request count, response time and total response time.

      val metricsWebClientFilterFunction = MetricsWebClientFilterFunction(meterRegistry, DefaultWebClientExchangeTagsProvider(), "webClientMetrics")
      WebClient.builder()
               .baseUrl("http://localhost:8080/test")
               .filter(metricsWebClientFilterFunction)
               .build()
    

    This will expose all the metrics of this WebClient Call in prometheus. Sample Prometheus Output:

    webClientMetrics_seconds_count{clientName="localhost",method="GET",status="200",uri="/test",} 2.0
    webClientMetrics_seconds_sum{clientName="localhost",method="GET",status="200",uri="/test",} 2.05474855
    webClientMetrics_seconds_max{clientName="localhost",method="GET",status="200",uri="/test",} 1.048698171
    

    To write custom metrics you can implement ExchangeFilterFunction and write your custom implementation for getting the metrics and add it in the WebClient Filter.