Home Spring Metrics For Simple Event Monitoring
Post
Cancel

Spring Metrics For Simple Event Monitoring

Sometimes (or all the time) you would want to know whats happening in your application’s life cycle. Spring Boot Metrics is just the right tool for application metrics in any Spring Boot Application. It exposes 2 metrics services, “Gauge” , “Counter” out of the box as well as an interface PublicMetrics to capture custom metrics.

We would use all 3 to capture application level metrics.

Before getting this to work add the Spring Boot Actuator Dependency (I assume you are using maven)

1
2
3
4
5
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
    <version>{version}</version>
  </dependency>

The first two are fairly simple. A simple 2 step process of initialize and use.

1. Gauge

A Gauge helps record a single value. Data type is double. Autowiring GaugeService before using it.

1
2
@Autowired
private GaugeService gaugeService;

then

1
gaugeService.submit("sample.metric", 20); //20 is sample metric value

2. Counter

A Counter records an increment or decrement. Data type is int.

1
2
@Autowired
private CounterService counterService;

this

1
counterService.increment("sample.metric"); //adds 1

or that

1
counterService.decrement("sample.metric"); //subtracts 1

3. PublicMetrics

This uses a different approach. Implement PublicMetrics.

then

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Component
public class CustomMetric implements PublicMetrics {

    public CustomMetric() {
    }

    @Override
    public Collection< Metric< ?> > metrics() {
        Collection< Metric< ?> > result = new LinkedHashSet<>();
        result.add(new Metric<>("sample.metric", 20)); //20 is sample metric value
        // u can add multiple metrics to results
        return result;
    }
}

Now that we’ve captured the metrics. How do we read it?

Goto http://localhost:{port}/metrics.

That’s about it.

This post is licensed under CC BY 4.0 by the author.