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 Applcation. 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)



        
         org.springframework.boot
         spring-boot-starter-actuator
         {version}
        

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

1. Gauge

A Gauge helps record a singule value. Data type is double. Autowirng GaugeService before using it.


@Autowired
private GaugeService gaugeService;

then


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

2. Counter

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


@Autowired
private CounterService counterService;

this


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

or that


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

3. PublicMetrics

This uses a different apporoach. Implement PublicMetrics.

then


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

Written on August 25, 2015