Micrometer helps you measure how your Spring Boot app is doing. It tracks things like how fast requests are or how many errors happen.
0
0
Metrics with Micrometer in Spring Boot
Introduction
You want to see how many users visit your website each minute.
You need to check if your app is slow or fast during certain times.
You want to count how many times a feature is used.
You want to watch for errors or failures in your app.
You want to send app performance data to monitoring tools like Prometheus.
Syntax
Spring Boot
import io.micrometer.core.instrument.MeterRegistry; import org.springframework.stereotype.Component; @Component public class MyMetrics { private final MeterRegistry meterRegistry; public MyMetrics(MeterRegistry meterRegistry) { this.meterRegistry = meterRegistry; } public void recordEvent() { meterRegistry.counter("myapp.events.count").increment(); } }
MeterRegistry is the main object to create and update metrics.
Use counters to count events, timers to measure durations, and gauges for current values.
Examples
This counts how many requests happened.
Spring Boot
meterRegistry.counter("requests.total").increment();This measures how long a block of code takes.
Spring Boot
import io.micrometer.core.instrument.Timer; Timer.Sample sample = Timer.start(meterRegistry); // code to time sample.stop(meterRegistry.timer("requests.latency"));
This tracks the current size of a queue.
Spring Boot
meterRegistry.gauge("queue.size", queue, Queue::size);Sample Program
This Spring Boot app has one endpoint /hello. Each time you visit it, Micrometer counts the request.
Spring Boot
package com.example.metricsdemo; import io.micrometer.core.instrument.MeterRegistry; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication public class MetricsDemoApplication { public static void main(String[] args) { SpringApplication.run(MetricsDemoApplication.class, args); } } @RestController class DemoController { private final MeterRegistry meterRegistry; public DemoController(MeterRegistry meterRegistry) { this.meterRegistry = meterRegistry; } @GetMapping("/hello") public String hello() { meterRegistry.counter("hello.requests.count").increment(); return "Hello, Micrometer!"; } }
OutputSuccess
Important Notes
Micrometer works with many monitoring systems like Prometheus, Datadog, and others.
Spring Boot auto-configures Micrometer if you add the right starter dependency.
Remember to name your metrics clearly so they are easy to understand later.
Summary
Micrometer helps track app performance and events easily.
Use counters, timers, and gauges for different types of metrics.
Spring Boot makes it simple to add Micrometer and start measuring.