What we would need to do is just autowire CounterService and add the call to counterService in the method:
@Autowired
private CounterService counterService;
...
public void sampleMethod() {
counterService.increment
("sampleservice.samplemethod.counter");
....
}
If we start the application and access /metrics endpoint, we should see
"counter.sampleservice.samplemethod.counter":...,
But what if we want to do something more sofisticated, for example, how many times the method was called in the last 5 minutes. Codahale metrics library gives us that functionality and it is integrated with Spring Boot.
You need to add dependency to your pom.xml:
<dependency>
<groupId>com.codahale.metrics</groupId>
<artifactId>metrics-core</artifactId>
</dependency>
Then you autowire MetricRegistry where you want to use metrics:
@Autowired
private MetricRegistry metricRegistry;
Now just register the metrics and start using it:
private Meter meter;
@PostConstruct
public void init() {
meter=metricRegistry.meter("example");
}
The metrics will show up in the /metrics endpoint:
"example.fiveMinuteRate": 0,
"example.oneMinuteRate": 0,
"example.count": 0,
"example.fifteenMinuteRate": 0,
No comments:
Post a Comment