Publishing Application Metrics to Azure Monitor Using Spring Boot 2 and Micrometer
Tags: devops, azure, java, springboot
Published: 2020-03-16 16:46:06

## Introduction

Observability is the activities that involve measuring, collecting, and analyzing various diagnostics signals from a system. These signals may include metrics, traces, logs, events, profiles and more.

Especially in a DevOps culture, where automation is key in order to stay productive, observability plays an important role. Your team should define alarms based on relevant system metrics to ensure that service level objectives are met. However, most modern applications are very complex distributed systems and it is hard to measure everything.

Luckily if you are using a managed platform many metrics will be collected for you automatically. Many cloud platforms like AWS, Azure and Google Cloud already collects metrics of your load balancers, application containers, applications requests, databases, and so on. What the cloud providers cannot offer, however, are application specific metrics, because they depend on your application logic.

Micrometer provides a simple facade for the JVM for a number of popular monitoring systems to collect application specific metrics. Currently, it supports the following monitoring systems: Azure Monitor, Netflix Atlas, CloudWatch, Datadog, Dynatrace, New Relic, Prometheus, And many other providers. Check this [documentation](https://micrometer.io/docs/concepts#_supported_monitoring_systems) for all available.

## Micrometer 

### MeterRegistry

A meter is an abstraction for a set of measurements about your application. A meter is uniquely identified by its name and tags. A meter registry holds meters. In Micrometer, a MeterRegistry is the core component used for registering meters.

The simplest form of the registry is SimpleMeterRegistry. But in most cases, we should use a MeterRegistry explicitly designed for our monitoring system; for Azure Monitor (AzureMonitorMeterRegistry), Prometheus (PrometheusMeterRegistry), Atlas (AtlasMeterRegistry).

In this article, we'll introduce the basic usage of Micrometer and its integration with Spring boot 2.

### Basic Meters

#### Counter 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/1kc6svulsv0srviqq955.PNG)

Counters report a single metric, a count. The Counter allows you to increment by a fixed amount, which must be positive. 

When building graphs and alerts off of counters, generally you should be most interested in measuring the rate at which some event is occurring over a given time interval. Consider a simple queue. Counters could be used to measure things like the rate at which items are being inserted and removed.

#### Gauge
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/zcfeuskmz8lg6kk16o4d.PNG)
Gauges are used to report a numeric state at a certain time. In contrast to a counter which you can increment, a gauge watches the state of an object and reports the current state whenever the metric is exported. A common example is the number of messages in a queue, or the number of connections in your connection pool.

#### Other metrics

Timer, Long Task Timer, Function-tracking counters, Function-tracking timers. I recommend read this article of [Rosner](https://dev.to/frosnerd/publishing-application-metrics-to-cloudwatch-using-micrometer-343f) and the [official documentation] (https://micrometer.io/docs/concepts).

## Azure Application Insights with Spring Boot 2 using Micrometer Registry Azure

This section explains how to use the Micrometer Azure registry in order to export your metrics to Azure Monitor.

### Set up Azure Application Insights

First, we need to create an [Application Insights Resource](https://docs.microsoft.com/en-us/azure/azure-monitor/app/create-new-resource).

Access the azure Portal and create the resource.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/2tw64g9jl8y2pjooddik.PNG)

Next step is define the subscription and Instance Details.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/r4umzshb9simqdf12vyu.PNG)

Access the resource created and get the Instrumentation Key.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/nie22xq1rbttaq73wlvk.png)

### Configuring your Spring boot 2 project

Add Azure dependencies in your Project:

```xml
        <dependency>
            <groupId>com.microsoft.azure</groupId>
            <artifactId>applicationinsights-spring-boot-starter</artifactId>
            <version>2.5.1</version>
        </dependency>
        <dependency>
            <groupId>com.microsoft.azure</groupId>
            <artifactId>azure-spring-boot-metrics-starter</artifactId>
            <version>2.2.0</version>
        </dependency>
```

Currently, Microsoft provides a Spring Boot Starter for automatically configuring Azure Application Insights: `applicationinsights-spring-boot-starter`.

Note that Microsoft also provide a `azure-spring-boot-metrics-starter`, for adds Micrometer monitoring support on top of the previous starter. Its current version, at the time of this writing, uses a different configuration key than `applicationinsights-spring-boot-starter`.

#### Add instrumentation key

Update `application.properties` file and use the same instrumentation key in both properties:

```xml
management.metrics.export.azuremonitor.instrumentation-key=XXXXXXXXXX
azure.application-insights.instrumentation-key=XXXXXXXXXX
```

#### Add custom Micrometer metric 

This is a example using a counter:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/dpv2fbwrn55j7n27sdy3.png)

The example project below is a simple User CRUD with HTTP Operations, the custom metric in this scenario is the number of users created who reported the phone.

{% github silviobuss/spring-boot-micrometer-azure %}

To generate the custom metric, just perform a POST request to endpoint http://localhost:8080/users with the JSON below:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/e04prn834l13ehiutdn5.PNG)

## Testing Azure Application Insights

Note that it is not necessary that your application is hosted on azure to have access to Application Insights and the monitor.

If everything is set up correctly, in the "Live Metrics Stream", you should see those scenarios running:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/zt3tilfsn3h1jvcrzruz.png)

We can see our custom metric in "Metrics":

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/prlwrgnq97t2o5pwhzx3.png)

## Conclusion

In this post we have seen how Micrometer works as a flexible layer of abstraction between your code and the monitoring systems. We can seen how its works and how is possible to monitoring a Java app implemented in Spring Boot 2 with Micrometer Azure layer.

<p><a href="https://twitter.com/silvio_buss"><img src="https://res.cloudinary.com/practicaldev/image/fetch/s--cMkfg_Vv--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/gmrz82bjwhej1f1iqb1e.png" alt="" loading="lazy"></a></p>

## References

Microsoft. https://docs.microsoft.com/en-us/azure/azure-monitor/app/micrometer-java

Frank Rosner. https://dev.to/frosnerd/publishing-application-metrics-to-cloudwatch-using-micrometer-343f