The English version of quarkus.io is the official project site. Translated sites are community supported on a best-effort basis.

Smallrye Metrics

The following guide demonstrates how a Quarkus application can use SmallRye Metrics, an implementation of the MicroProfile Metrics specification.

SmallRye Metrics allows applications to gather metrics and statistics that provide insights into what is happening inside an application. The metrics can be read remotely using the JSON or OpenMetrics format to be processed by additional tools such as Prometheus and stored for analysis and visualization.

Apart from application-specific metrics described in this guide, you may also use built-in metrics exposed by various Quarkus extensions. These are described in the guide for each particular extension that supports built-in metrics.

Micrometer is the recommended approach to metrics for Quarkus. Use the SmallRye Metrics extension when it is required to retain MicroProfile specification compatibility.

前提条件

このガイドを完成させるには、以下が必要です:

  • 約15分

  • IDE

  • JDK 11+ がインストールされ、 JAVA_HOME が適切に設定されていること

  • Apache Maven 3.8.1+

  • 使用したい場合、 Quarkus CLI

  • ネイティブ実行可能ファイルをビルドしたい場合、MandrelまたはGraalVM(あるいはネイティブなコンテナビルドを使用する場合はDocker)をインストールし、 適切に設定していること

アーキテクチャ

In this example, we build a very simple microservice that offers one REST endpoint. This endpoint serves for determining whether a number is prime. The implementation class is annotated with certain metric annotations so that while responding to users' requests, certain metrics are gathered. The meaning of each metric is explained later.

ソリューション

We recommend that you follow the instructions in the next sections and create the application step by step. However, you can skip to the completed example.

  1. Clone the Git repository:

    git clone https://github.com/quarkusio/quarkus-quickstarts.git

Creating a Maven project

To create a new project:

CLI
quarkus create app org.acme:microprofile-metrics-quickstart \
    --extension=resteasy-reactive,smallrye-metrics \
    --no-code
cd microprofile-metrics-quickstart

Gradleプロジェクトを作成するには、 --gradle または --gradle-kotlin-dsl オプションを追加します。

Quarkus CLIのインストール方法については、Quarkus CLIガイドをご参照ください。

Maven
mvn io.quarkus.platform:quarkus-maven-plugin:2.11.1.Final:create \
    -DprojectGroupId=org.acme \
    -DprojectArtifactId=microprofile-metrics-quickstart \
    -Dextensions="resteasy-reactive,smallrye-metrics" \
    -DnoCode
cd microprofile-metrics-quickstart

Gradleプロジェクトを作成するには、 -DbuildTool=gradle または -DbuildTool=gradle-kotlin-dsl オプションを追加します。

This command generates a Quarkus project that uses the smallrye-metrics extension.

すでにQuarkusプロジェクトが設定されている場合は、プロジェクトのベースディレクトリーで以下のコマンドを実行することで、プロジェクトに smallrye-metrics エクステンションを追加することができます。

CLI
quarkus extension add 'smallrye-metrics'
Maven
./mvnw quarkus:add-extension -Dextensions="smallrye-metrics"
Gradle
./gradlew addExtension --extensions="smallrye-metrics"

This adds the following to your build file:

pom.xml
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-smallrye-metrics</artifactId>
</dependency>
build.gradle
implementation("io.quarkus:quarkus-smallrye-metrics")

Writing an application

The following procedures create a Quarkus application that consists of a single class that implements an algorithm for checking whether a number is prime. This algorithm is exposed over a REST interface. Additionally, specific annotations are required to ensure that the desired metrics are calculated over time and can be exported for manual analysis or processing by additional tooling.

The application will gather the following metrics:

  • performedChecks: A counter that increases by one each time the user asks about a number.

  • highestPrimeNumberSoFar: A gauge that stores the highest number asked about by the user if the number was determined to be prime.

  • checksTimer: A compound metric that benchmarks how much time the primality tests take. Additional details are provided later.

The full source code looks as follows:

package org.acme.microprofile.metrics;

import org.eclipse.microprofile.metrics.MetricUnits;
import org.eclipse.microprofile.metrics.annotation.Counted;
import org.eclipse.microprofile.metrics.annotation.Gauge;
import org.eclipse.microprofile.metrics.annotation.Timed;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/")
public class PrimeNumberChecker {

    private long highestPrimeNumberSoFar = 2;

    @GET
    @Path("/{number}")
    @Produces(MediaType.TEXT_PLAIN)
    @Counted(name = "performedChecks", description = "How many primality checks have been performed.")
    @Timed(name = "checksTimer", description = "A measure of how long it takes to perform the primality test.", unit = MetricUnits.MILLISECONDS)
    public String checkIfPrime(long number) {
        if (number < 1) {
            return "Only natural numbers can be prime numbers.";
        }
        if (number == 1) {
            return "1 is not prime.";
        }
        if (number == 2) {
            return "2 is prime.";
        }
        if (number % 2 == 0) {
            return number + " is not prime, it is divisible by 2.";
        }
        for (int i = 3; i < Math.floor(Math.sqrt(number)) + 1; i = i + 2) {
            if (number % i == 0) {
                return number + " is not prime, is divisible by " + i + ".";
            }
        }
        if (number > highestPrimeNumberSoFar) {
            highestPrimeNumberSoFar = number;
        }
        return number + " is prime.";
    }

    @Gauge(name = "highestPrimeNumberSoFar", unit = MetricUnits.NONE, description = "Highest prime number so far.")
    public Long highestPrimeNumberSoFar() {
        return highestPrimeNumberSoFar;
    }

}

アプリケーションの実行と使用

To execute the application created in Writing an application, do the following:

  1. Run the microservice in dev mode:

    CLI
    quarkus dev
    Maven
    ./mvnw quarkus:dev
    Gradle
    ./gradlew --console=plain quarkusDev
  2. Generate values for the metrics.

    1. Query the endpoint to determine whether some numbers are prime numbers:

      curl localhost:8080/350

      アプリでは、350は2で割れるので素数ではないと回答します。

      • For large prime numbers, the test takes more time.

        curl localhost:8080/629521085409773

        The application will respond that 629521085409773 is a prime number.

    2. Perform additional calls with numbers of your choice.

  3. Review the generated metrics:

    curl -H"Accept: application/json" localhost:8080/q/metrics/application

    You will receive a response such as:

    {
      "org.acme.microprofile.metrics.PrimeNumberChecker.checksTimer" : {			                    (1)
        "p50": 217.231273,										                                        (2)
        "p75": 217.231273,
        "p95": 217.231273,
        "p98": 217.231273,
        "p99": 217.231273,
        "p999": 217.231273,
        "min": 0.58961,										                                            (3)
        "mean": 112.15909190834819,								                                        (4)
        "max": 217.231273,									                                            (5)
        "stddev": 108.2721053982776,							    	                                (6)
        "count": 2,											                                            (7)
        "meanRate": 0.04943519091742238,							                                    (8)
        "oneMinRate": 0.2232140583080189,
        "fiveMinRate": 0.3559527083952095,
        "fifteenMinRate": 0.38474303050928976
      },
      "org.acme.microprofile.metrics.PrimeNumberChecker.performedChecks" : 2,		                    (9)
      "org.acme.microprofile.metrics.PrimeNumberChecker.highestPrimeNumberSoFar" : 629521085409773		(10)
    }
1 checksTimer: A compound metric that benchmarks how much time the primality tests take. All durations are measured in milliseconds. It consists of these values below.
2 p50, p75, p95, p99, p999: Percentiles of the durations. For example, the value in p95 means that 95 % of the measurements were faster than this duration.
3 min: The shortest duration it took to perform a primality test was probably performed for a small number.
4 mean : 計測された所要時間の平均値。
5 max : 最長所要時間、おそらく大きな素数に対して行われたものです。
6 stddev : 標準偏差。
7 count: The number of observations, the value of which is the same as performedChecks.
8 meanRate, oneMinRate, fiveMinRate, fifteenMinRate : 平均スループットと 1、5、および 15 分間の指数関数的に加重された移動平均スループット。
9 performedChecks : ユーザーが数字を尋ねるたびに1つ増えるカウンター。
10 highestPrimeNumberSoFar: A gauge that stores the highest number that was asked about by the user and which was determined to be prime.
JSON形式ではなくOpenMetricsのエクスポートを希望する場合は、コマンドラインから -H"Accept: application/json" 引数を削除してください。
設定リファレンス

ビルド時に固定される設定プロパティ - それ以外の設定プロパティは実行時に上書き可能

Configuration property

タイプ

デフォルト

The path to the metrics handler.

Environment variable: QUARKUS_SMALLRYE_METRICS_PATH

string

metrics

Whether metrics published by Quarkus extensions should be enabled.

Environment variable: QUARKUS_SMALLRYE_METRICS_EXTENSIONS_ENABLED

boolean

true

Apply Micrometer compatibility mode, where instead of regular 'base' and 'vendor' metrics, Quarkus exposes the same 'jvm' metrics that Micrometer does. Application metrics are unaffected by this mode. The use case is to facilitate migration from Micrometer-based metrics, because original dashboards for JVM metrics will continue working without having to rewrite them.

Environment variable: QUARKUS_SMALLRYE_METRICS_MICROMETER_COMPATIBILITY

boolean

false

Whether detailed JAX-RS metrics should be enabled. See MicroProfile Metrics: Optional REST metrics.

Environment variable: QUARKUS_SMALLRYE_METRICS_JAXRS_ENABLED

boolean

false