Groovy / Maven

Collect Metrics with Micronaut

Learn how to collect standard and custom metrics with the Micronaut framework.

Burt Beckwith
On this guide
In this section

Getting Started

In this guide, we will create a Micronaut application written in Groovy.

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:

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.

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 \
    --build=maven \
    --lang=groovy \
    --test=spock
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, and http-client 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:

src/main/resources/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 Timer metric that contains the total time, max time, and count.

@Counted

Creates a Counter metric 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:

pom.xml
<dependency>
    <groupId>io.micronaut.flyway</groupId>
    <artifactId>micronaut-flyway</artifactId>
    <scope>compile</scope>
</dependency>

We will enable Flyway in the Micronaut configuration file and configure it to perform migrations on one of the defined data sources.

src/main/resources/application.properties
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:

src/main/resources/db/migration/V1__schema.sql
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:

groovy/src/main/groovy/example/micronaut/Book.groovy

BookRepository

Next, create the BookRepository interface to define database operations. Micronaut Data will implement the interface at compilation time:

groovy/src/main/groovy/example/micronaut/BookRepository.groovy

Data populator class

Create a DataPopulator class to create some example database entries when the application starts:

groovy/src/main/groovy/example/micronaut/DataPopulator.groovy

BookController

Create BookController to access Book instances (and trigger JDBC metric data):

groovy/src/main/groovy/example/micronaut/BookController.groovy

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:

groovy/src/main/groovy/example/micronaut/crypto/BitcoinPrice.groovy

Kucoin Declarative HTTP Client

Create a declarative Micronaut HTTP Client interface that will be implemented at compile time:

groovy/src/main/groovy/example/micronaut/crypto/PriceClient.groovy

HTTP Service Configuration

Modify application.properties to configure the URL for the kucoin Service ID:

src/main/resources/application.properties

Service

Create a CryptoService class that uses PriceClient and updates three custom meters:

groovy/src/main/groovy/example/micronaut/crypto/CryptoService.groovy

Testing the Application

Create the src/test/resources/application-test.properties configuration file for tests.

src/test/resources/application-test.properties

Create a test class to verify metrics functionality:

groovy/src/test/groovy/example/micronaut/MetricsSpec.groovy

Create an additional test class to verify the custom metrics:

groovy/src/test/groovy/example/micronaut/CryptoUpdatesSpec.groovy
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 spock.lang.AutoCleanup
import spock.lang.Shared
import spock.lang.Specification

import static java.util.concurrent.TimeUnit.MILLISECONDS

class CryptoUpdatesSpec extends Specification {

    @Shared
    @AutoCleanup
    EmbeddedServer kucoinEmbeddedServer = ApplicationContext.run(EmbeddedServer,
            ['spec.name': 'MetricsTestKucoin'])

    @Shared
    @AutoCleanup
    EmbeddedServer embeddedServer = ApplicationContext.run(EmbeddedServer,
            ['micronaut.http.services.kucoin.url': 'http://localhost:' + kucoinEmbeddedServer.port])

    void 'test crypto updates'() {
        given:
        CryptoService cryptoService = embeddedServer.applicationContext.getBean(CryptoService)
        MeterRegistry meterRegistry = embeddedServer.applicationContext.getBean(MeterRegistry)

        when:
        Counter counter = meterRegistry.counter('bitcoin.price.checks')
        Timer timer = meterRegistry.timer('bitcoin.price.time')

        then:
        counter.count() == 0
        timer.totalTime(MILLISECONDS) == 0

        when:
        int checks = 3
        checks.times {
            cryptoService.updatePrice()
        }

        then:
        counter.count() == checks
        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"
                                                 |  }
                                                 |}'''.stripMargin()

        @Get('/api/v1/market/orderbook/level1')
        String latest(@QueryValue String symbol) {
            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:

./mvnw test

Running the Application

To run the application, use the ./mvnw mn: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:

./mvnw mn:run -Dmn.appArgs="-crypto.updateFrequency=5s"

You can retrieve a list of known metrics using cURL:

curl localhost:8080/metrics

The 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"
}

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).