Collect Metrics with Micronaut
Learn how to collect standard and custom metrics with the Micronaut framework.
On this guide
In this section
Getting Started
In this guide, we will create a Micronaut application written in Java.
We’ll use Micronaut Micrometer to expose application metric data with Micrometer.
What you will need
To complete this guide, you will need the following:
-
Some time on your hands
-
A decent text editor or IDE (e.g. IntelliJ IDEA)
-
JDK 21 or greater installed with
JAVA_HOMEconfigured appropriately
Solution
We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.
-
Download and unzip the source
Writing the Application
Create an application using the Micronaut Command Line Interface or with Micronaut Launch.
mn create-app example.micronaut.micronautguide \
--features=micrometer-annotation,data-jdbc,flyway,validation,http-client,graalvm \
--build=gradle \
--lang=java \
--test=junit|
Note
|
If you don’t specify the --build argument, Gradle with the Kotlin DSL is used as the build tool. If you don’t specify the --lang argument, Java is used as the language.If you don’t specify the --test argument, JUnit is used for Java and Kotlin, and Spock is used for Groovy.
|
The previous command creates a Micronaut application with the default package example.micronaut in a directory named micronautguide.
If you use Micronaut Launch, select Micronaut Application as application type and add micrometer-annotation, data-jdbc, flyway, validation, http-client, and graalvm features.
|
Note
|
If you have an existing Micronaut application and want to add the functionality described here, you can view the dependency and configuration changes from the specified features, and apply those changes to your application. |
Metrics Configuration
Several groups of metrics are enabled by default. These include system metrics (JVM info, uptime, etc.), as well as metrics tracking web requests, DataSource activity, and others. Overall metrics can be enabled or disabled, and groups can be individually enabled or disabled in configuration.
Add the following to application.properties:
Custom Metrics
If the built-in metrics aren’t enough, you can easily add custom metrics with the following annotations.
- @Timed
-
Creates a
Timermetric that contains the total time, max time, and count. - @Counted
-
Creates a
Countermetric that only contains a count.
If you want to create your own gauge, you can inject io.micrometer.core.instrument.MeterRegistry to your bean.
Data Source Metrics
DataSource metrics are enabled by default if you use HikariCP (the default), Tomcat JDBC, or the Commons DBCP connection pool.
Database Migration with Flyway
We need a way to create the database schema. For that, we use Micronaut integration with Flyway.
Flyway automates schema changes, significantly simplifying schema management tasks, such as migrating, rolling back, and reproducing in multiple environments.
Add the following snippet to include the necessary dependencies:
implementation("io.micronaut.flyway:micronaut-flyway")We will enable Flyway in the Micronaut configuration file and configure it to perform migrations on one of the defined data sources.
|
Note
|
Configuring multiple data sources is as simple as enabling Flyway for each one. You can also specify directories that will be used for migrating each data source. Review the Micronaut Flyway documentation for additional details. |
Flyway migration will be automatically triggered before your Micronaut application starts. Flyway will read migration commands in the resources/db/migration/ directory, execute them if necessary, and verify that the configured data source is consistent with them.
Create the following migration files with the database schema creation:
DROP TABLE IF EXISTS book;
CREATE TABLE book (
id BIGINT GENERATED BY DEFAULT AS IDENTITY,
name VARCHAR(255) NOT NULL,
isbn VARCHAR(255) NOT NULL UNIQUE
);During application startup, Flyway will execute the SQL file and create the schema needed for the application.
Domain
Create a Book domain class that uses Micronaut Data JDBC:
BookRepository
Next, create the BookRepository interface to define database operations. Micronaut Data will implement the interface at compilation time:
Data populator class
Create a DataPopulator class to create some example database entries when the application starts:
BookController
Create BookController to access Book instances (and trigger JDBC metric data):
Custom Metrics
To see custom metrics in action, create a service that periodically retrieves the current Bitcoin price in USD using REST.
Model
We’ll need a data class to represent the REST response. Create the BitcoinPrice class:
Kucoin Declarative HTTP Client
Create a declarative Micronaut HTTP Client interface that will be implemented at compile time:
HTTP Service Configuration
Modify application.properties to configure the URL for the kucoin Service ID:
Service
Create a CryptoService class that uses PriceClient and updates three custom meters:
Testing the Application
Create the src/test/resources/application-test.properties configuration file for tests.
Create a test class to verify metrics functionality:
Create an additional test class to verify the custom metrics:
package example.micronaut;
import example.micronaut.crypto.CryptoService;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import io.micronaut.context.ApplicationContext;
import io.micronaut.context.annotation.Requires;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.QueryValue;
import io.micronaut.runtime.server.EmbeddedServer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import java.util.Collections;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS;
@TestInstance(PER_CLASS)
public class CryptoUpdatesTest {
EmbeddedServer embeddedServer;
EmbeddedServer kucoinEmbeddedServer;
@BeforeAll
void beforeAll() {
kucoinEmbeddedServer = ApplicationContext.run(EmbeddedServer.class,
Collections.singletonMap("spec.name", "MetricsTestKucoin"));
embeddedServer = ApplicationContext.run(EmbeddedServer.class,
Collections.singletonMap("micronaut.http.services.kucoin.url", "http://localhost:" + kucoinEmbeddedServer.getPort()));
}
@AfterAll
void afterAll() {
embeddedServer.close();
kucoinEmbeddedServer.close();
}
@Test
void testCryptoUpdates() {
CryptoService cryptoService = embeddedServer.getApplicationContext().getBean(CryptoService.class);
MeterRegistry meterRegistry = embeddedServer.getApplicationContext().getBean(MeterRegistry.class);
Counter counter = meterRegistry.counter("bitcoin.price.checks");
Timer timer = meterRegistry.timer("bitcoin.price.time");
assertEquals(0, counter.count(), 0.000001);
assertEquals(0, timer.totalTime(MILLISECONDS));
int checks = 3;
for (int i = 0; i < checks; i++) {
cryptoService.updatePrice();
}
assertEquals(checks, counter.count(), 0.000001);
assertTrue(timer.totalTime(MILLISECONDS) > 0);
}
@Requires(property = "spec.name", value = "MetricsTestKucoin")
@Controller
static class MockKucoinController {
private static final String RESPONSE = """
{
"code":"200000",
"data":{
"time":1654865889872,
"sequence":"1630823934334",
"price":"29670.4",
"size":"0.00008436",
"bestBid":"29666.4",
"bestBidSize":"0.16848947",
"bestAsk":"29666.5",
"bestAskSize":"2.37840044"
}
}""";
@Get("/api/v1/market/orderbook/level1")
String latest(@QueryValue String symbol) {
return RESPONSE;
}
}
}The previous test creates two Micronaut embedded servers. One mocks the kucoin API, the other is our application. The test uses @Requires to conditionally load a controller only for the kucoin bean context.
We used an identifier with @Client, which makes it easy to point our HTTP client to the mock server.
Running the tests
To run the tests:
./gradlew testThen open build/reports/tests/test/index.html in a browser to see the results.
Running the Application
To run the application, use the ./gradlew run command, which starts the application on port 8080.
Alternatively, to make the Bitcoin price update occur more frequently to see the effects on metrics, start the application with a config override to update every five seconds:
./gradlew run --args="-crypto.updateFrequency=5s"You can retrieve a list of known metrics using cURL:
curl localhost:8080/metricsThe response should look like this:
{
"names": [
"bitcoin.price.checks",
"bitcoin.price.latest",
"bitcoin.price.time",
"executor",
"executor.active",
"executor.completed",
"executor.pool.core",
"executor.pool.max",
"executor.pool.size",
"executor.queue.remaining",
"executor.queued",
"hikaricp.connections",
"hikaricp.connections.acquire",
"hikaricp.connections.active",
...
"jvm.threads.peak",
"jvm.threads.states",
"logback.events",
"process.cpu.usage",
"process.files.max",
"process.files.open",
"process.start.time",
"process.uptime",
"system.cpu.count",
"system.cpu.usage",
"system.load.average.1m"
]
}After the application has been running for a bit and has made a few Bitcoin price checks, we can view the related metric values:
curl localhost:8080/metrics/bitcoin.price.latest{
"measurements": [{ "statistic": "VALUE", "value": 29659.0 } ],
"name": "bitcoin.price.latest"
}curl localhost:8080/metrics/bitcoin.price.checks{
"measurements": [{ "statistic": "COUNT", "value": 5.0 } ],
"name": "bitcoin.price.checks"
}curl localhost:8080/metrics/bitcoin.price.time{
"baseUnit": "seconds",
"measurements": [
{ "statistic": "COUNT", "value": 5.0 },
{ "statistic": "TOTAL_TIME", "value": 2.525546791 },
{ "statistic": "MAX", "value": 0.851958216 }
],
"name": "bitcoin.price.time"
}Generate a Micronaut Application Native Executable with GraalVM
We will use GraalVM, an advanced JDK with ahead-of-time Native Image compilation, to generate a native executable of this Micronaut application.
Compiling Micronaut applications ahead of time with GraalVM significantly improves startup time and reduces the memory footprint of JVM-based applications.
|
Note
|
Only Java and Kotlin projects support using GraalVM’s native-image tool. Groovy relies heavily on reflection, which is only partially supported by GraalVM.
|
GraalVM Installation
sdk install java 25.0.2-graalFor installation on Windows, or for a manual installation on Linux or Mac, see the GraalVM Getting Started documentation.
The previous command installs Oracle GraalVM, which is free to use in production and free to redistribute, at no cost, under the GraalVM Free Terms and Conditions.
Alternatively, you can use the GraalVM Community Edition:
sdk install java 25.0.2-graalceNative Executable Generation
To generate a native executable using Gradle, run:
./gradlew nativeCompileThe native executable is created in build/native/nativeCompile directory and can be run with build/native/nativeCompile/micronautguide.
It is possible to customize the name of the native executable or pass additional parameters to GraalVM:
Start the native image and run the cURL commands above to see that the application works the same way as before, with faster startup and response times.
Next Steps
In combination with the /metrics endpoint, you often want to register a specific type of reporter. See the Micronaut Micrometer documentation to learn about the supported libraries for reporting metrics.
License
|
Note
|
All guides are released with an Apache License 2.0 for the code and a Creative Commons Attribution 4.0 license for the writing and media (images). |