Jon Abraham
Jon Abraham

Reputation: 955

MeterRegistry Counter does not increment

I am trying to implement error - 404 metric counter where i only want to count the number of 404 requests occurring within my api. I am not seeing the count to go up even though i am trying to mock multiple 404 request to my api. Below is my metric class -

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;


@ControllerAdvice
public class MetricController {

    private MeterRegistry meterRegistry;


    @Autowired
    public MetricController(MeterRegistry meterRegistry){
        this.meterRegistry=meterRegistry;
    }


    private void countHttpStatus(HttpStatus status){
      Counter count=meterRegistry.counter(String.format("http.status.%d",status.value()));
      count.increment();

    }


    @Bean
    ApplicationRunner runner(){
        return args ->{
          countHttpStatus(HttpStatus.NOT_FOUND);


        };
    }


}

when i hit this end-point - http://localhost:8081/actuator/metrics/http.status.404

then i see below response -

{
    "name": "http.status.404",
    "description": null,
    "baseUnit": null,
    "measurements": [
        {
            "statistic": "COUNT",
            "value": 1
        }
    ],
    "availableTags": []
}

I want this count to go up if i am hitting my api with multiple 404's

Upvotes: 3

Views: 5966

Answers (1)

Andrea Ciccotta
Andrea Ciccotta

Reputation: 672

your code does the following:

  • create ApplicationRunner runner once (because is annotated as @Bean)
  • calls countHttpStatus method once (because is called from ApplicationRunner runner beans at creation time)
  • increments http.status.404 metric once (because is done from countHttpStatus method invoked once at ApplicationRunner runner @Bean creation time)
  • nothing else, this flow is no longer invoked so the value is 1 as you have

Upvotes: 1

Related Questions