therefore I am sometimes reluctant to add new metrics because it requires me to inject MetricRegistry

also MetricRegistry must be stubbed in unit tests

Micrometer's tagline is:

Think SLF4J, but for metrics

It's actually quite accurate. Whenever I need a Logger I don't inject LoggerFactory, instead I simply use static methods available everywhere. The same goes for Micrometer, I simply use static factory methods on globally available Metrics class:

That's it! You can put metrics anywhere you like without polluting your constructor with MetricRegistry. The API is very similar, e.g.:

concurrent.increment()

One major difference is gauges vs. counters. In Dropwizard Metrics counters can go up and down whereas in Micrometer counter must increase monotonically. I thought it's a bug... Counter is used in simple scenarios like counting how many requests succeeded. So how can we measure things like the number of concurrent requests or queue length? With gauges, but it's slightly convoluted.

Did you notice how Metrics.gauge() takes a new LongAdder() as an argument? And returns it? This way we create a gauge that track (by periodically polling for value) any instance of Number class (e.g. AtomicLong or LongAdder). We can modify the returned LongAdder and its current value will be reflected by the gauge. Neat! Moreover, there are helper methods like gaugeCollectionSize() and gaugeMapSize() that take any Collection or Map respectively - and are quite self-explanatory.

Built-in JVM metrics

Micrometer also has a bunch of built-in system and JVM metrics, for example:

LogbackMetrics - number of log messages per each log level. You can watch e.g. error rate

ProcessorMetrics- average system load

JvmMemoryMetrics - memory usage, split by area

JvmThreadMetrics - number of thread (live, daemon, peak...)

JvmGcMetrics - GC promotion rate, etc.

Most of these are registered by default by Spring Boot. The last two of them will be available as well. By having all these metrics we can actually enhance our dashboard quite a bit:

The dashboard definition for Grafana is available on GitHub. Notice how this application uses about 100 MiB of RAM while sustaining almost two thousand concurrent connections (!) Also less than 45 live threads compared to thousands of concurrent connections is impressive.

It's worth mentioning that the setup of Micrometer in Spring Boot is really simple. First, add the appropriate dependency:

Labels

Comments

Thank you some much tomasz.One can only acknowledge your deep understanding when you decide to share a topic.This series really is helpful to migrate to micrometer.It was equally interesting to see spring 5.0 in action in the previous posts