Counter Metrics for Rest Api's in SpringBoot

Mangla :

What would be the best approach to count how many times an API is being triggered with its successful/failure response in spring boot.

What I have in my mind is using a post construct to start a new thread when application comes up and when an api is being called and then using a counter service for each new unique request to count how many api's is being triggered by that particular request and how many of them are successful or failed.

Recommend some new approaches if you guys have any.

Szymon Stepniak :

You don't have to create if from scratch, you can simply use Spring Boot Actuator that has this feature built-in. Just add following dependency to your project:

pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Actuator exposes e.g. /metrics endpoint and here you can find a counters for all responses - each counter starts with counter.status.{{status_code}}.{{endpoint}}.

For example, I have simple demo application with /hello endpoint. Any time I call this endpoint metric counter.status.200.hello will be increased. When I access /metrics endpoint I can see something like:

{
  "mem": 586013,
  "mem.free": 324496,
  "processors": 8,
  "instance.uptime": 144496,
  "uptime": 149950,
  "systemload.average": 0.52,
  "heap.committed": 522240,
  "heap.init": 251904,
  "heap.used": 197743,
  "heap": 3580928,
  "nonheap.committed": 64960,
  "nonheap.init": 2496,
  "nonheap.used": 63773,
  "nonheap": 0,
  "threads.peak": 42,
  "threads.daemon": 25,
  "threads.totalStarted": 54,
  "threads": 27,
  "classes": 8938,
  "classes.loaded": 8938,
  "classes.unloaded": 0,
  "gc.ps_scavenge.count": 8,
  "gc.ps_scavenge.time": 54,
  "gc.ps_marksweep.count": 2,
  "gc.ps_marksweep.time": 65,
  "gauge.response.star-star.favicon.ico": 1,
  "counter.status.200.star-star": 2,
  "counter.status.304.star-star": 2,
  "counter.status.200.metrics.name": 2,
  "counter.status.200.star-star.favicon.ico": 5,
  "gauge.response.star-star": 3,
  "gauge.response.hello": 5,
  "gauge.response.metrics.name": 3,
  "counter.status.200.hello": 2,
  "counter.status.404.metrics.name": 1,
  "httpsessions.max": -1,
  "httpsessions.active": 0,
  "datasource.primary.active": 0,
  "datasource.primary.usage": 0
}

I can also access single metric, e.g. /metrics/counter.status.200.hello which returns only:

{
  "counter.status.200.hello": 2
}

By default /metrics endpoint is secured. For your local dev you can turn it of by adding:

management:
  security:
    enabled: false

to your application.yml or

management.security.enabled=false

to application.properties if you use that one.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=468576&siteId=1