Add custom metrics to Java applications using OpenTelemetry SDK metrics

In the previous tutorial, I guided you through OpenTelemetry with the Logging exporter to log information about requests to the application. By default, we will see mainly information about tracers logged. To display more information about metrics, you can add additional code using the OpenTelemetry SDK metrics library. How is it in detail? Let’s find out together in this tutorial!

I will reuse the example in the article Integrate OpenTelemetry with Java applications, and will add the OpenTelemetry SDK metrics dependency to this application’s project as follows:

Our project is Spring Boot and since it already has a managed version of OpenTelemetry SDK, you don’t need to declare the version for OpenTelemetry SDK anymore, guys!

Now, we will add a metric to count the number of requests to the “/hello” request of the example application. For each incoming request, the number of requests to the application will increase by 1.

To do this, first, we will initialize the object of the Meter class using the GlobalOpenTelemetry class of the OpenTelemetry SDK library first, as follows:

The parameter of the static meterBuilder() method is the name of the metric, so you can quickly search based on this name, so please give it a reasonable name to search quickly!

Next, I will define a variable to hold information about the number of requests to the application’s “/hello” request. You can use the object of OpenTelemetry SDK metrics’ LongCounter class to hold this information:

To make each time, a request to the request “/hello”, the number of requests will increase by 1, you can use the add() method of the LongBuilder object as follows:

Now, run this application again using OpenTelemetry’s Logging Exporter and then request to http://localhost:8080/hello 3 times, wait a little while, you will see the following logline:

If you look closely at this logline, you will see that it is the logline of OpenTelemetry about the metric using the LoggerMetricExporter class, the name of InstrumentationScopeInfo is “io.opentelemetry.metrics.hello” as I set it above, for the metric “helloCounter” then its value is 3.

That’s it, we have successfully added a custom metric to our Java application and used the LoggingExporter to log this information to the console!

Add Comment