このページを編集

guides/telemetry-micrometer.adoc

micrometer は、メトリクス収集のための抽象化レイヤーを提供します。 カウンター、ゲージ、タイマー、ディストリビューションサマリーなどの基本的なメータータイプの API と、さまざまなバックエンドモニタリングシステムのメトリクスの収集と伝達を一般化する MeterRegistry API を定義します。

このドキュメントは、 QuarkusのObservabilityリファレンスガイド の一部です。

Micrometer is the recommended approach to metrics for Quarkus.
By default, the metrics are exposed on the main HTTP server. If you would like to surface metrics from a separate management port, see the Managed interface section.

マイクロメーターとモニタリングシステムのエクステンション

Quarkus Micrometer エクステンションは、Micrometer プロジェクトと同じ構造になっています。 quarkus-micrometer エクステンションは、Micrometer のコアサポートとランタイムの統合を提供します。 他の Quarkus や Quarkiverse のエクステンションは、Quarkus Micrometer エクステンションを使用して、他のモニタリングシステムのサポートを提供します。

Quarkus エクステンション:

  • micrometer

  • micrometer-registry-prometheus

  • micrometer-opentelemetry

Quarkiverse エクステンション (このリストは完全でない可能性あり):

  • micrometer-registry-azure-monitor

  • micrometer-registry-datadog

  • micrometer-registry-graphite

  • micrometer-registry-influx

  • micrometer-registry-jmx

  • micrometer-registry-newrelic-telemetry

  • micrometer-registry-otlp

  • micrometer-registry-signalfx

  • micrometer-registry-stackdriver

  • micrometer-registry-statsd

例えば、アプリケーションに Prometheus メトリクスのサポートを追加するには、 micrometer-registry-prometheus エクステンションを使用します。 これにより、Quarkus MicrometerエクステンションとMicrometerコアライブラリが依存ライブラリとして追加されます。

(プロジェクトディレクトリで)以下のコマンドを使用して、エクステンションをプロジェクトに追加します:

CLI
quarkus extension add micrometer-registry-prometheus
Maven
./mvnw quarkus:add-extension -Dextensions='micrometer-registry-prometheus'
Gradle
./gradlew addExtension --extensions='micrometer-registry-prometheus'

これにより、ビルドファイルに以下が追加されます:

pom.xml
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-micrometer-registry-prometheus</artifactId>
</dependency>
build.gradle
implementation("io.quarkus:quarkus-micrometer-registry-prometheus")

これで準備完了です!

他のメーターレジストリーエクステンションにも同様のプロセスが適用されます。 たとえば、Micrometer StackDriver MeterRegistry を使用するには、 Quarkiverse の quarkus-micrometer-registry-stackdriver エクステンションを使用します。

CLI
quarkus extension add io.quarkiverse.micrometer.registry:quarkus-micrometer-registry-stackdriver
Maven
./mvnw quarkus:add-extension -Dextensions='io.quarkiverse.micrometer.registry:quarkus-micrometer-registry-stackdriver'
Gradle
./gradlew addExtension --extensions='io.quarkiverse.micrometer.registry:quarkus-micrometer-registry-stackdriver'
pom.xml
<dependency>
    <groupId>io.quarkiverse.micrometer.registry</groupId>
    <artifactId>quarkus-micrometer-registry-stackdriver</artifactId>
</dependency>
build.gradle
implementation("io.quarkiverse.micrometer.registry:quarkus-micrometer-registry-stackdriver")

その他のレジストリ実装

使用する Micrometer レジストリに関連エクステンションがない場合は、 quarkus-micrometer エクステンションを使用し、Micrometer メーターレジストリの依存関係を直接取り込んでください:

pom.xml
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-micrometer</artifactId>
</dependency>
<dependency>
    <groupId>com.acme</groupId>
    <artifactId>custom-micrometer-registry</artifactId>
    <version>...</version>
</dependency>
build.gradle
implementation("io.quarkus:quarkus-micrometer")
implementation("com.acme:custom-micrometer-registry")

次に、次のセクションで説明するように、MeterRegistry を設定して初期化するために、独自のプロバイダを指定する必要があります。

OpenTelemetry を介した Micrometer メトリクスの送信

quarkus-micrometer-opentelemetry エクステンションを使用すると、Quarkus で利用可能な Micrometer API と既存のすべての自動インスツルメンテーションを使用しながら、OpenTelemetry ですべてのテレメトリーを送信できます。

これは、OpenTelemetry SDK で実装された Micrometer レジストリによって実現され、Micrometer メトリクス、OpenTelemetry トレース、およびログを OTLP プロトコルを使用した統合テレメトリー出力に統合できます。

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

CLI
quarkus extension add micrometer-opentelemetry
Maven
./mvnw quarkus:add-extension -Dextensions='micrometer-opentelemetry'
Gradle
./gradlew addExtension --extensions='micrometer-opentelemetry'

これにより、ビルドファイルに以下が追加されます:

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

カスタマイズされたMeterRegistryの作成

必要に応じて、カスタム @Produces メソッドを使用して、独自の MeterRegistry を作成および設定します。

以下の例では、StatsDで使用される行フォーマットをカスタマイズしています。

@Produces
@Singleton (1)
public StatsdMeterRegistry createStatsdMeterRegistry(StatsdConfig statsdConfig, Clock clock) { (2)
    // define what to do with lines
    Consumer<String> lineLogger = line -> logger.info(line);

    // inject a configuration object, and then customize the line builder
    return StatsdMeterRegistry.builder(statsdConfig)
          .clock(clock)
          .lineSink(lineLogger)
          .build();
}
1 メソッドは @Singleton を返します。
2 このメソッドは、特定のタイプの MeterRegistry を返します。

This example corresponds to the following instructions in the Micrometer documentation: Micrometer StatsD: Customizing the Metrics Sink

MicroProfile Config を使用して、レジストリーを設定するために必要な設定属性を挿入します。 quarkus-micrometer-registry-statsd などのほとんどの Micrometer レジストリーエクステンションは、Quarkus 設定モデルと統合されたレジストリー固有の設定オブジェクトを提供します。 Quarkiverse GitHub リポジトリー は、便利な実装リファレンスになります。

独自のメトリクスの作成

メトリクスデータは、時間の経過に伴うデータの変化を観察するために集計されて使用されます。 このデータは、傾向分析、異常検出、アラートに使用されます。 データは、バックエンドモニタリングシステムによって時系列データベースに保存され、新しい値が系列の末尾に追加されます。

Metrics are constructed lazily. You may not see any data for the metric you’re looking for until you’ve performed an action that will create it, like visiting an endpoint.

命名規則

メーター名では、ドットを使用してセグメントを区切る必要があります (例: a.name.like.this)。 Micrometer は命名規則を適用し、登録されたメーター名をバックエンドモニタリングシステムの期待に一致するように変換します。

タイマーの registry.timer("http.server.requests") 宣言に基づいて、適用された命名規則により、さまざまな監視システム向けに以下のメトリクスが発行されます。

  • Prometheus: http_server_requests_duration_seconds

  • Atlas: httpServerRequests

  • Graphite: http.server.requests

  • InfluxDB: http_server_requests

集計のディメンションを定義する

メトリクスは単一の数値測定ですが、多くの場合、追加データが一緒にキャプチャーされます。この補助データは、分析のためにメトリクスをグループ化または集計するために使用されます。 Micrometer API では、このディメンションデータをタグと呼びますが、他のドキュメントソースでは「ラベル」または「属性」と呼ばれることもあります。

Micrometer は主に、ディメンションデータ (キー/値のペアで強化されたメトリクス名) をサポートするバックエンドモニタリングシステム用に構築されています。 フラットなメトリクス名のみをサポートする階層型システムの場合、Micrometer はキー/値のペアのセット (キーでソート) をフラット化し、名前に追加します。

タグは、メーターが MeterRegistry に登録されるとき、またはMeter Filter を使用して指定できます。

タグの命名 に関するその他のアドバイスについては、Micrometerのドキュメントを参照してください。

Each unique combination of metric name and dimension produces a unique time series. Using an unbounded set of dimensional data can lead to a "cardinality explosion", an exponential increase in the creation of new time series.

MeterRegistry への参照を取得する

メーターを登録するには、Micrometer エクステンションによって設定および維持される MeterRegistry への参照が必要です。

MeterRegistry への参照を取得するには、次のいずれかの方法を使用します。

  1. CDIコンストラクタ注入の使用:

    package org.acme.micrometer;
    
    import io.micrometer.core.instrument.MeterRegistry;
    
    import jakarta.ws.rs.GET;
    import jakarta.ws.rs.Path;
    import jakarta.ws.rs.Produces;
    
    @Path("/example")
    @Produces("text/plain")
    public class ExampleResource {
    
        private final MeterRegistry registry;
    
        ExampleResource(MeterRegistry registry) {
            this.registry = registry;
        }
    }
  2. MeterRegistry メンバー変数を使用し、@Inject を使用します。

        @Inject
        MeterRegistry registry;
  3. グローバル MeterRegistry を使用します。

        MeterRegistry registry = Metrics.globalRegistry;

ゲージ

ゲージは、車のスピードメーターのように、時間の経過とともに増加または減少する値を測定します。 ゲージは、キャッシュまたはコレクションの統計を監視するときに役立ちます。

ゲージの値は設定されずにサンプリングされます。 測定間でゲージに関連付けられた値がどのように変化したかについての記録はありません。

Micrometer はゲージを作成するためのいくつかのメカニズムを提供します。

  1. コレクションのサイズを監視するためにコレクションの構築をラップします。

    List<String> list = registry.gaugeCollectionSize("fantastic.list", (1)
            Tags.of("key", "value") // optional (2)
            new ArrayList<>());  (3)
    1 ドット区切りの規則を使用して、新しいゲージ list.size を作成します。
    2 ゲージに tags を関連付けます。 ゲージタグの値は一定であり、構築時に割り当てる必要があります。
    3 サイズを監視する必要のある配列リストを構築します。
  2. ビルダーを使用して、関数を呼び出すゲージを作成します。

    Gauge.builder("jvm.threads.peak", threadBean, ThreadMXBean::getPeakThreadCount) (1)
        .baseUnit(BaseUnits.THREADS) // optional (2)
        .description("The peak live thread count...") // optional (3)
        .tags("key", "value") // optional (4)
        .register(registry); (5)
    1 jvm.threads.peak という新しいゲージを作成し、threadBean (ThreadMXBean のインスタンス) で getPeakThreadCount を呼び出します。
    2 基本単位を定義します。事前定義された値については BaseUnits.java を参照してください。
    3 ゲージの説明を入力してください
    4 ゲージに tags を関連付けます。
    5 MeterRegistry にゲージを登録する

詳細と例については、Micrometer ドキュメントの Gauges を参照してください。 特筆すべきは2つの特別なケースです: 時間を測定するための TimeGauge と、いくつかの基準をまとめて報告するための MultiGauge です。

Micrometer does not create strong references to the objects it observes by default. Depending on the registry, Micrometer either omits gauges that observe objects that have been garbage-collected entirely or uses NaN (not a number) as the observed value.

ゲージはいつ使用したらよいですか? 他のものを使用できない場合にのみゲージを使用してください。 ゲージは他のメーターに比べて使い方が簡単ではない場合があります。 測定対象をカウントできる場合 (値が常に増加するため) は、代わりにカウンターを使用します。

カウンター

カウンターは増加する値のみを測定します。 カウンターを作成するには、以下のいずれかの方法を使用します。

  1. MeterRegistry の便利なメソッドを使用します。

    registry.counter("example.prime.number", "type", "prime"); (1) (2)
    1 example.prime.number はカウンター名です。
    2 type は、値が prime であるディメンションタグです。
  2. 説明と単位を指定するには、Counter.builder を使用します。

    Counter.builder("count.me") (1)
        .baseUnit("beans")            // optional (2)
        .description("a description") // optional (3)
        .tags("region", "test")       // optional (4)
        .register(registry);
    1 count.me という新しいカウンターを作成します。
    2 カスタムベースユニットを定義します。事前定義された値については BaseUnits.java を参照してください。
    3 カウンターの説明を入力してください
    4 カウンターに タグ を関連付けます。
  3. メソッドに アノテーションを付与 します。

    @Counted(value = "counted.method", extraTags = { "extra", "annotated" }) (1) (2)
    void countThisMethod(){
        ...
    }
    1 CDI インターセプターは counted.method というカウンターを作成して登録します。
    2 インターセプターが作成したカウンターには、値が "annotated" の "extra" ディメンションタグが付きます。

常時増加する関数が返す結果を測定するために使用できる、あまり一般的でない FunctionCounter を含む、より詳細な情報と例については、マイクロメータのドキュメントの カウンタ を参照してください。

カウンターはいつ使用したらよいですか? 時間を計ったり要約したりできない作業の場合は、カウンターを使用します。 値がどのように変化しているかを詳しく知りたい場合は、 タイマー (測定の基本単位が時間の場合) またはディストリビューションサマリーの方が、 より適切な場合もあります。

サマリーとタイマー

Micrometer のタイマーとディストリビューションサマリーは非常に似ています。両方のメーターはデータを記録し、追加のヒストグラムまたはパーセンタイルデータを取得できます。ディストリビューションサマリーは任意のタイプのデータに使用できますが、タイマーは時間と期間の測定に最適化されています。

タイマーとディストリビューションサマリーは、少なくとも 3 つの値を内部に保存します。

  • 記録されたすべての値の合計としての集計

  • 記録された値の数 (カウンター)

  • 減少する時間ウィンドウ内で見られる最高値 (ゲージ)

ディストリビューションサマリーを作成する

ディストリビューションサマリーを使用して、時間ではなく値を記録します。 ディストリビューションサマリーを作成するには、次のいずれかの方法を使用します。

  1. MeterRegistry の便利なメソッドを使用します。

    registry.summary("bytes.written", "protocol", "http"); (1) (2)
    1 bytes.written はサマリー名です
    2 protocol は、値が http のディメンションタグです。
  2. 説明と単位を指定するには、DistributionSummary.builder を使用します。

    DistributionSummary.builder("response.size") (1)
        .baseUnit("bytes")            // optional (2)
        .description("a description") // optional (3)
        .tags("protocol", "http")     // optional (4)
        .register(registry);
    1 response.size という新しいディストリビューションサマリーを作成します。
    2 基本単位として bytes を使用します。事前定義された値については BaseUnits.java を参照してください。
    3 ディストリビューションサマリーの説明を入力します
    4 ディストリビューションサマリーに tags を関連付けます。

タイマーの作成

Timers measure short-duration latencies and how often they occur. Negative values are not supported, and longer durations could cause an overflow of the total time (Long.MAX_VALUE nanoseconds (292.3 years)).

Use one of the following methods to construct a timer.

  1. MeterRegistry の便利なメソッドを使用します。

    registry.timer("fabric.selection", "primary", "blue"); (1) (2)
    1 `fabric.selection`はサマリー名です。
    2 primary は、値が blue のディメンションタグです。
  2. 説明と単位を指定するには、Timer.builder を使用します。

    Timer.builder("my.timer")        (1) (2)
        .description("description ") // optional (3)
        .tags("region", "test")      // optional (4)
        .register(registry);
    1 my.timer という新しいタイマーを作成します。
    2 タイマーは時間を測定し、それをモニタリングバックエンドに必要な単位に変換します。
    3 ディストリビューションサマリーの説明を入力します
    4 タイマーに tags を関連付けます。
  3. メソッドに アノテーションを付与 します。

    @Timed(value = "call", extraTags = {"region", "test"}) (1) (2)
    1 CDI インターセプターは call と呼ばれるタイマーを作成して登録します。
    2 インターセプターが作成したタイマーには、値が "test" の "region" ディメンションタグが付きます。

タイマーで時間を計測する

Micrometer provides the following convenience mechanisms for recording durations.

  1. Runnable の呼び出しをラップします。

    timer.record(() -> noReturnValue());
  2. Callable の呼び出しをラップします。

    timer.recordCallable(() -> returnValue());
  3. 繰り返される呼び出し用にラップされた Runnable を作成します。

    Runnable r = timer.wrap(() -> noReturnValue());
  4. 繰り返される呼び出し用にラップされた Callable を作成します。

    Callable c = timer.wrap(() -> returnValue());
  5. より複雑なコードパスには Sample を使用します。

    Sample sample = Timer.start(registry); (1)
    
    doStuff; (2)
    
    sample.stop(registry.timer("my.timer", "response", response.status())); (3)
    1 タイマーの開始を記録するサンプルを作成します。
    2 サンプルはコンテキストとして渡すことができます。
    3 サンプルが停止されるときのタイマーを選択できます。この例では、タイマーを識別するタグとしてレスポンスステータスを使用しますが、これは処理が完了するまでわかりません。

ヒストグラムとパーセンタイル

タイマと分布サマリはどちらも、ヒストグラム・データ、事前計算されたパーセンタイル、サービス・レベル目標(SLO)境界などの追加統計を出力するように設定できます。 両タイプのメモリ・フットプリントの推定など、詳細な情報や例については、Micrometerドキュメントの Timer and Distribution Summaries を参照してください。

タイマーとディストリビューションサマリーに関連付けられたカウント、合計、およびヒストグラムデータは、ディメンション全体 (または一連のインスタンス全体) にわたって再集計できます。

事前計算されたパーセンタイル値は再集計できません。パーセンタイルはデータセットごとに一意です (この測定値のコレクションの 90 パーセンタイルなど)。

自動的に生成されたメトリクス

HTTP サーバー

Micrometer エクステンションは、HTTP サーバーのリクエストの時間を自動的に計測します。Prometheus のタイマーの命名規則に従い、http_server_requests_seconds_counthttp_server_requests_seconds_sumhttp_server_requests_seconds_max を参照してください。要求された URI、HTTP メソッド (GET、POST など)、ステータスコード (200、302、404 など)、そしてより一般的な結果フィールドのための次元ラベルが追加されました。

エンドポイントの無視

quarkus.micrometer.binder.http-server.ignore-patterns プロパティを使用して、HTTP エンドポイントの測定を無効にすることができます。このプロパティには、無視すべきURIパスを特定する単純な正規表現のマッチパターンをコンマで区切ったリストを指定できます。例えば、 quarkus.micrometer.binder.http-server.ignore-patterns=/example/prime/[0-9]+ を設定すると、以下へのリクエストが無視されます。 http://localhost:8080/example/prime/7919 へのリクエストは無視されます。 http://localhost:8080/example/gauge/7919 へのリクエストは、依然として計測されます。

URIテンプレート

Micrometer エクステンションは、パスパラメーターを含む URI をテンプレート形式で表現するために最善を尽くします。 上記の例を使用すると、http://localhost:8080/example/prime/7919 へのリクエストは、http_server_requests_seconds_* メトリクスの属性として、 uri=/example/prime/{number} という値で表示される必要があります。

正しいURLが特定できない場合は、 quarkus.micrometer.binder.http-server.match-patterns プロパティを使用します。このプロパティには、単純な正規表現パターンと置換文字列の関連性を定義するコンマ区切りのリストを指定できます。例えば、 quarkus.micrometer.binder.http-server.match-patterns=/example/prime/=/example/{jellybeans}` を設定すると、要求された uri が `/example/prime/[0-9] に一致した場合、uri 属性に /example/{jellybeans} の値が使用されます。

エクスポートされるメトリクス形式

デフォルトでは、メトリクスはPrometheusのフォーマット application/openmetrics-text を使用してエクスポートされます。 Accept リクエストヘッダを plain/text ( curl -H "Accept: plain/text" localhost:8080/q/metrics/ ) に指定することで、以前のフォーマットに戻すことも可能です。

Netty メモリ管理メトリクス

Netty のメモリ管理メトリクスは重要です。なぜなら、Quarkus は Eclipse Vert.x 上に構築されており、Vert.x は Java でリアクティブアプリケーションを作成するために Netty 上に構築されたフレームワークだからです。Quarkus で命令型プログラミングスタイルを使用する場合でも、内部的には Vert.x によってリアクティブな方法で便利に処理されます。

要するに、Netty は 効率的な メモリ管理システムを非同期アプリケーション向けに提供します。これは、ヒープ (JVM ヒープに保存される) や直接メモリ (JVM メモリの外部に割り当てられる) を含むさまざまな種類のメモリ割り当て戦略と、割り当てを最適化し、ガベージコレクション (GC) のオーバーヘッドを削減するための バッファー プーリング メカニズム を提供します。

Nettyにおけるメモリカテゴリー

Nettyは主に2つのメモリカテゴリーを使用します。

  1. ヒープメモリ

    • JVMヒープ (byte[]) から割り当てられます。

    • ガベージコレクターによって管理されます。

    • ソケット経由で送信する前にデータをダイレクトメモリにコピーする必要があるため、I/O 操作が遅くなります。

  2. ダイレクトメモリ

    • ByteBuffer.allocateDirect() を使用して JVM ヒープ外に割り当てられます。

    • ガベージコレクターによって管理されないため、GCの負荷を軽減します。

    • 不要なコピーを回避するため、I/O 操作が高速です。

-XX:MaxRAMPercentage に非常に高い値を使用すること (利用可能なRAMのほとんどをJavaヒープに割り当てること) は、Nettyのネイティブメモリ割り当て用の領域を残すことが重要であるため、Quarkusアプリケーションでは推奨されません。

これらのNettyメトリクスは、どのくらいの領域が必要かを評価するのに役立ちます。

プーリングメカニズム

Nettyは、メモリ割り当てのオーバーヘッドとフラグメンテーションを削減するために PooledByteBufAllocator を使用します。これは、jemallocスタイルのアリーナシステム (参照: jemalloc/jemalloc) に基づいており、以下を含みます。

  • アリーナ: 割り当てを管理する大きなメモリブロック。

  • チャンク: アリーナ内のメモリセグメント (通常サイズは16MB)。

  • ページ: チャンクの固定サイズ部分 (通常は8KB)。

  • サブページ: 小さいオブジェクト用のページ内のより小さな割り当て。

  • スレッドローカルキャッシュ: 頻繁に使用される小さなバッファー用のスレッドごとのキャッシュで、競合を軽減します。

Nettyメモリ管理のメトリクス

Micrometerメトリクスは、Nettyのアロケーターからの主要なメトリクスを報告し、メモリ使用量、固定メモリ、プーリング効率、キャッシュ動作の監視に役立ちます。

1. Memory Usage Metrics (Every allocator)

これらのメトリクスは、Nettyアロケーターによる現在のメモリ使用量 (バイト単位) を追跡します。

メトリクス名 説明 タイプ タグ

allocator.memory.used

アロケーターによって現在使用されているメモリ量

ゲージ

memory_type=[heap, direct], name=allocator-name

2. Pooled Allocator - Pinned Memory Metrics

固定メモリとは、アクティブな参照があるためリサイクルできず、アロケーターによる再利用を妨げるバッファーを指します。 多い 数は、何らかのリーク (参照が解放されていないため) を示している可能性があります。

メトリクス名 説明 タイプ タグ

allocator.memory.pinned

再利用できない固定メモリの量

ゲージ

memory_type=[heap, direct], name=allocator-name

3. Pooled Allocator - Arena Metrics

アリーナ (大きなサイズのメモリ) は、メモリチャンクをグループ化することでメモリ割り当てを効率的に管理します。したがって、このメトリクスは、特定のアロケーターに割り当てられたアリーナの数です。

メトリクス名 説明 タイプ タグ

allocator.pooled.arenas

メモリ割り当てを処理するアリーナの数

ゲージ

memory_type=[heap, direct]

4. Cache Size Metrics

Nettyは、頻繁なメモリ割り当てを回避し、パフォーマンスを向上させるために、特定のThread内に小さなバッファーをキャッシュします。同じスレッドがメモリを必要とする場合、まず自身のキャッシュをチェックします。これは、イベントループスレッドモデル (スレッド数が少ない) のおかげで特に効率的です。なお、現在、tinyキャッシュはsmallキャッシュにマージされています。

メトリクス名 説明 タイプ タグ

allocator.pooled.cache.size

バッファーキャッシュのサイズ

ゲージ

cache_type=[small, normal]

5. Thread-Local Cache Metrics

これらのメトリクスは、メモリプーリングに使用されるアクティブなスレッドローカルキャッシュの数を示します。これはキャッシュサイズメトリクス (キャッシュがサイズであり、これがキャッシュの数である) を補完します。

メトリクス名 説明 タイプ タグ

allocator.pooled.threadlocal.caches

バッファー用のスレッドローカルキャッシュの数

ゲージ

なし

6. Chunk Size Metrics

チャンクは、Netty のアリーナにおけるメモリー割り当ての主要な単位です。

メトリクス名 説明 タイプ タグ

allocator.pooled.chunk.size

プールされたアロケーターのメモリーチャンクサイズ

ゲージ

なし

アンプール

これは、新しいバッファーを直接作成し、プーリングメカニズムをバイパスするための静的メソッドを提供するユーティリティークラスを使用します。ユーザーは割り当てられたバッファーも解放する必要があります。

UnpooledByteBufAllocator を使用する一部のライブラリーが、一部のヒープバッファーを解放しない場合があることが 報告されています。これにより、メモリーがもはや予約されていない場合でも、報告された割り当ては減少しません。これは、報告されたメモリーに天文学的な値をもたらす可能性があります。

デバッグ

高い割り当て値が報告された場合、それが実際のメモリーリークであるかどうかを判断する方法は 2 つあります。

  • Netty で文書化されているように、 リーク検出 を有効にすることで。例:

java -Dio.netty.leakDetection.level=advanced ...
  • アプリケーションからのメモリーダンプを検査する。

Micrometer のカスタマイズ

Quarkus provides a variety of way to customize Micrometer.

Use MeterFilter to customize emitted tags and metrics

Micrometerは MeterFilter インスタンスを使って、 MeterRegistry インスタンスが出力するメトリクスをカスタマイズします。 Micrometer エクステンションは、 MeterFilter のCDI Beanを検出して、 MeterRegistry インスタンスを初期化するときにそれを使います。

@Singleton
public class CustomConfiguration {

    @ConfigProperty(name = "deployment.env")
    String deploymentEnv;

    /** Define common tags that apply only to a Prometheus Registry */
    @Produces
    @Singleton
    @MeterFilterConstraint(applyTo = PrometheusMeterRegistry.class)
    public MeterFilter configurePrometheusRegistries() {
        return MeterFilter.commonTags(Arrays.asList(
                Tag.of("registry", "prometheus")));
    }

    /** Define common tags that apply globally */
    @Produces
    @Singleton
    public MeterFilter configureAllRegistries() {
        return MeterFilter.commonTags(Arrays.asList(
                Tag.of("env", deploymentEnv)));
    }

    /** Enable histogram buckets for a specific timer */
    @Produces
    @Singleton
    public MeterFilter enableHistogram() {
        return new MeterFilter() {
            @Override
            public DistributionStatisticConfig configure(Meter.Id id, DistributionStatisticConfig config) {
                if(id.getName().startsWith("myservice")) {
                    return DistributionStatisticConfig.builder()
                        .percentiles(0.5, 0.95)     // median and 95th percentile, not aggregable
                        .percentilesHistogram(true) // histogram buckets (e.g. prometheus histogram_quantile)
                        .build()
                        .merge(config);
                }
                return config;
            }
        };
    }
}

In this example, a singleton CDI bean will produce two different MeterFilter beans. One will be applied only to Prometheus MeterRegistry instances (using the @MeterFilterConstraint qualifier), and another will be applied to all MeterRegistry instances. An application configuration property is also injected and used as a tag value. Additional examples of MeterFilters can be found in the official documentation.

Use HttpServerMetricsTagsContributor for server HTTP requests

io.quarkus.micrometer.runtime.HttpServerMetricsTagsContributor を実装する CDI Bean を提供することで、ユーザーコードは HTTP リクエストとレスポンスの詳細に基づいて任意のタグを提供できます。

When creating tags using this interface, it’s important to limit the cardinality of the values, otherwise there is a risk of severely degrading the metrics system’s capacity.

Use HttpClientMetricsTagsContributor for client HTTP requests

io.quarkus.micrometer.runtime.HttpClientMetricsTagsContributor を実装する CDI Bean を提供することで、ユーザーコードは HTTP リクエストとレスポンスの詳細に基づいて任意のタグを提供できます。

Use MeterRegistryCustomizer for arbitrary customizations to meter registries

io.quarkus.micrometer.runtime.MeterRegistryCustomizer を実装する CDI Bean を提供することで、ユーザーコードはアクティブ化された任意の MeterRegistry の設定を変更できます。 実装に @io.quarkus.micrometer.runtime.MeterRegistryCustomizerConstraint アノテーションが付与されていない限り、このカスタマイズはすべての MeterRegistry インスタンスに適用されます。

Micrometerはアノテーションをサポートしていますか?

Micrometerでは、メソッドに追加できる2つのアノテーション、 @Counted@Timed が定義されています。 @Timed アノテーションは、メソッドの実行をラップし、アノテーション自体に定義されているタグに加えて、次のタグを出力します:class、method、exception("none "または検出された例外のシンプルなクラス名)。

@Counted および @Timed へのパラメーターに @MeterTag アノテーションを付けて、意味のあるタグ値を動的に割り当てることができます。

MeterTag.resolver は、メソッドのパラメータからタグを抽出するために使用できます。これは、 io.micrometer.common.annotation.ValueResolver を実装する Bean を作成し、@MeterTag(resolver=CustomResolver.class) クラスを参照することで実現できます。

MeterTag.expression もサポートされていますが、式の評価が可能な io.micrometer.common.annotation.ValueExpressionResolver を実装する Bean を作成し、式を評価する必要があります。

enum Currency { USD, EUR }

@Singleton
class EnumOrdinalResolver implements ValueResolver {
    @Override
    public String resolve(Object parameter) {
        if(parameter instanceof Enum) {
            return String.valueOf(((Enum<?>) parameter).ordinal());
        }
        return null;
    }
}

@Singleton
public class MyExpressionResolver implements ValueExpressionResolver {
    @Override
    public String resolve(String expression, Object parameter) {
        return someParser.parse(expression).evaluate(parameter);
    }
}

// tags = type=with_enum, currency=${currency.toString()}
@Timed(value="time_something", extraTags = {"type", "with_enum"})
public Something calculateSomething(@MeterTag Currency currency) { ... }

// tags = type=with_enum, the_currency=${currency.toString()}
@Timed(value="time_something", extraTags = {"type", "with_enum"})
public Something calculateSomething(@MeterTag(key="the_currency") Currency currency) { ... }

// tags = type=with_enum, currency=${currency.ordinal()}
@Timed(value="time_something", extraTags = {"type", "with_enum"})
public Something calculateSomething(@MeterTag(resolver=EnumOrdinalResolver.class) Currency currency) { ... }

// tags = type=with_enum, currency=${currency.ordinal()}
@Timed(value="time_something", extraTags = {"type", "with_enum"})
public Something calculateSomething(@MeterTag(expression="currency.ordinal()") Currency currency) { ... }
Provided tag values MUST BE of LOW-CARDINALITY. High-cardinality values can lead to performance and storage issues in your metrics backend (a "cardinality explosion"). Tag values should not use end-user data, since those could be high-cardinality.

REST エンドポイントメソッドや Vert.x ルートなどの多くのメソッドは、すぐに使用できる Micrometer エクステンションによってカウントされ、時間が計測されます。

マネジメントインターフェース

By default, the metrics are exposed on the main HTTP server.

アプリケーション設定で quarkus.management.enabled=true を設定することで、それらを別のネットワークインターフェイスとポートで公開できます。 このプロパティーはビルド時のプロパティーである点に注意してください。 値は、実行時にオーバーライドできません。

If you enable the management interface without customizing the management network interface and port, the metrics are exposed under: http://0.0.0.0:9000/q/metrics.

公開される各形式のパスは、以下を使用して設定できます。

quarkus.micrometer.export.json.enabled=true (1)
quarkus.micrometer.export.json.path=metrics/json
quarkus.micrometer.export.prometheus.path=metrics/prometheus
1 JSON メトリクスの有効化

このような設定にすると、JSON メトリクスは http://0.0.0.0:9000/q/metrics/json から利用可能になります。Prometheus メトリクスは http://0.0.0.0:9000/q/metrics/prometheus から利用可能になります。

詳しくは、 マネジメントインターフェイスのリファレンス を参照してください。

設定リファレンス

ビルド時に固定される設定プロパティ - 他のすべての設定プロパティは、実行時にオーバーライド可能

Configuration property

タイプ

デフォルト

Micrometer metrics support.

Micrometer metrics support is enabled by default.

Environment variable: QUARKUS_MICROMETER_ENABLED

Show more

boolean

true

Micrometer MeterRegistry discovery.

Micrometer MeterRegistry implementations discovered on the classpath will be enabled automatically by default.

Environment variable: QUARKUS_MICROMETER_REGISTRY_ENABLED_DEFAULT

Show more

boolean

true

Micrometer MeterBinder discovery. In other words, enables the automatic metrics instrumentation.

Micrometer MeterBinder implementations discovered on the classpath will be enabled automatically by default. In other words, automatic metrics instrumentation will be ON by default.

quarkus.micrometer.binder.enable-all overrides this property, meaning when this is set to false, and enable-all is true, discovery of all MeterBinder will still happen.

Environment variable: QUARKUS_MICROMETER_BINDER_ENABLED_DEFAULT

Show more

boolean

true

Comma-separated list of additional HTTP methods to allow in the {@code method} metric tag, beyond the standard RFC 9110/5789/9512 methods (GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH, QUERY).

Non-standard HTTP methods are replaced with {@code UNKNOWN} by default to prevent metrics cardinality explosion. Use this property to allow specific custom methods (e.g. WebDAV methods like {@code PROPFIND}).

The total number of methods to track cannot exceed 32.

Environment variable: QUARKUS_MICROMETER_BINDER_HTTP_ADDITIONAL_METHODS

Show more

文字列のリスト

Outbound HTTP request metrics support.

Support for HTTP client metrics will be enabled if Micrometer support is enabled, the REST client feature is enabled, and either this value is true, or this value is unset and quarkus.micrometer.binder-enabled-default is true.

Environment variable: QUARKUS_MICROMETER_BINDER_HTTP_CLIENT_ENABLED

Show more

boolean

Inbound HTTP metrics support.

Support for HTTP server metrics will be enabled if Micrometer support is enabled, an extension serving HTTP traffic is enabled, and either this value is true, or this value is unset and quarkus.micrometer.binder-enabled-default is true.

Environment variable: QUARKUS_MICROMETER_BINDER_HTTP_SERVER_ENABLED

Show more

boolean

Micrometer JVM metrics support.

Support for JVM metrics will be enabled if Micrometer support is enabled, and either this value is true, or this value is unset and quarkus.micrometer.binder-enabled-default is true.

Environment variable: QUARKUS_MICROMETER_BINDER_JVM

Show more

boolean

Kafka metrics support.

Support for Kafka metrics will be enabled if Micrometer support is enabled, the Kafka Consumer or Producer interface is on the classpath and either this value is true, or this value is unset and quarkus.micrometer.binder-enabled-default is true.

Environment variable: QUARKUS_MICROMETER_BINDER_KAFKA_ENABLED

Show more

boolean

Redis client metrics support.

Support for Redis metrics will be enabled if Micrometer support is enabled, the Quarkus Redis client extension is on the classpath and either this value is true, or this value is unset and quarkus.micrometer.binder-enabled-default is true.

Environment variable: QUARKUS_MICROMETER_BINDER_REDIS_ENABLED

Show more

boolean

Stork metrics support.

Support for Stork metrics will be enabled if Micrometer support is enabled, the Quarkus Stork extension is on the classpath and either this value is true, or this value is unset and quarkus.micrometer.binder-enabled-default is true.

Environment variable: QUARKUS_MICROMETER_BINDER_STORK_ENABLED

Show more

boolean

gRPC Server metrics support.

Support for gRPC server metrics will be enabled if Micrometer support is enabled, the gRPC server interfaces are on the classpath and either this value is true, or this value is unset and quarkus.micrometer.binder-enabled-default is true.

Environment variable: QUARKUS_MICROMETER_BINDER_GRPC_SERVER_ENABLED

Show more

boolean

gRPC Client metrics support.

Support for gRPC client metrics will be enabled if Micrometer support is enabled, the gRPC client interfaces are on the classpath and either this value is true, or this value is unset and quarkus.micrometer.binder-enabled-default is true.

Environment variable: QUARKUS_MICROMETER_BINDER_GRPC_CLIENT_ENABLED

Show more

boolean

Kafka metrics support.

Support for Reactive Messaging metrics will be enabled if Micrometer support is enabled, MessageObservationCollector interface is on the classpath and either this value is true, or this value is unset and quarkus.micrometer.binder-enabled-default is true.

Environment variable: QUARKUS_MICROMETER_BINDER_MESSAGING_ENABLED

Show more

boolean

Virtual Threads metrics support.

Support for virtual threads metrics will be enabled if Micrometer support is enabled, this value is set to true (default), the JVM supports virtual threads (Java 21+) and the quarkus.micrometer.binder-enabled-default property is true.

Environment variable: QUARKUS_MICROMETER_BINDER_VIRTUAL_THREADS_ENABLED

Show more

boolean

The tags to be added to the metrics. Empty by default. When set, tags are passed as: key1=value1,key2=value2.

Environment variable: QUARKUS_MICROMETER_BINDER_VIRTUAL_THREADS_TAGS

Show more

文字列のリスト

Micrometer System metrics support.

Support for System metrics will be enabled if Micrometer support is enabled, and either this value is true, or this value is unset and quarkus.micrometer.binder-enabled-default is true.

Environment variable: QUARKUS_MICROMETER_BINDER_SYSTEM

Show more

boolean

Vert.x metrics support.

Support for Vert.x metrics will be enabled if Micrometer support is enabled, Vert.x MetricsOptions is on the classpath and either this value is true, or this value is unset and quarkus.micrometer.binder-enabled-default is true.

Environment variable: QUARKUS_MICROMETER_BINDER_VERTX_ENABLED

Show more

boolean

Netty metrics support.

Support for Netty metrics will be enabled if Micrometer support is enabled, the Netty allocator classes are on the classpath and either this value is true, or this value is unset and quarkus.micrometer.binder-enabled-default is true.

Environment variable: QUARKUS_MICROMETER_BINDER_NETTY_ENABLED

Show more

boolean

Enable all binders. Activates all metrics regardless off their particular default.

This property has precedence over all BinderConfig binders. In other words, if the quarkus.micrometer.binder.jvm is set to false and quarkus.micrometer.binder.enabled-all is set to true, all JVM metrics will be enabled.

Also takes precedence over quarkus.micrometer.binder-enabled-default, if binder discover is disabled, discovery of all metrics will still happen.

Environment variable: QUARKUS_MICROMETER_BINDER_ENABLE_ALL

Show more

boolean

false

Support for export to JSON format. Off by default.

Environment variable: QUARKUS_MICROMETER_EXPORT_JSON_ENABLED

Show more

boolean

false

The path for the JSON metrics endpoint. The default value is metrics. By default, this value will be resolved as a path relative to ${quarkus.http.non-application-root-path}. If the management interface is enabled, the value will be resolved as a path relative to ${quarkus.management.root-path}.

Environment variable: QUARKUS_MICROMETER_EXPORT_JSON_PATH

Show more

string

metrics

Statistics like max, percentiles, and histogram counts decay over time to give greater weight to recent samples. Samples are accumulated to such statistics in ring buffers which rotate after the expiry, with this buffer length.

Environment variable: QUARKUS_MICROMETER_EXPORT_JSON_BUFFER_LENGTH

Show more

int

3

Statistics like max, percentiles, and histogram counts decay over time to give greater weight to recent samples. Samples are accumulated to such statistics in ring buffers which rotate after this expiry, with a particular buffer length.

Environment variable: QUARKUS_MICROMETER_EXPORT_JSON_EXPIRY

Show more

Duration 

P3D

Support for export to Prometheus.

Support for Prometheus will be enabled if Micrometer support is enabled, the PrometheusMeterRegistry is on the classpath and either this value is true, or this value is unset and quarkus.micrometer.registry-enabled-default is true.

Environment variable: QUARKUS_MICROMETER_EXPORT_PROMETHEUS_ENABLED

Show more

boolean

The path for the prometheus metrics endpoint (produces text/plain). The default value is metrics and is resolved relative to the non-application endpoint (q), e.g. ${quarkus.http.root-path}/${quarkus.http.non-application-root-path}/metrics. If an absolute path is specified (/metrics), the prometheus endpoint will be served from the configured path.

If the management interface is enabled, the value will be resolved as a path relative to ${quarkus.management.root-path} (q by default), e.g. http://${quarkus.management.host}:${quarkus.management.port}/${quarkus.management.root-path}/metrics. If an absolute path is specified (/metrics), the prometheus endpoint will be served from the configured path, e.g. http://${quarkus.management.host}:${quarkus.management.port}/metrics.

Environment variable: QUARKUS_MICROMETER_EXPORT_PROMETHEUS_PATH

Show more

string

metrics

By default, this extension will create a Prometheus MeterRegistry instance.

Use this attribute to veto the creation of the default Prometheus MeterRegistry.

Environment variable: QUARKUS_MICROMETER_EXPORT_PROMETHEUS_DEFAULT_REGISTRY

Show more

boolean

true

Comma-separated list of regular expressions used to specify uri labels in http metrics.

Outbount HTTP client instrumentation will attempt to transform parameterized resource paths, /item/123, into a generic form, /item/{id}, to reduce the cardinality of uri label values.

Patterns specified here will take precedence over those computed values.

For example, if /item/\\\\d+=/item/custom or /item/[0-9]+=/item/custom is specified in this list, a request to a matching path (/item/123) will use the specified replacement value (/item/custom) as the value for the uri label. Note that backslashes must be double escaped as \\\\.

Environment variable: QUARKUS_MICROMETER_BINDER_HTTP_CLIENT_MATCH_PATTERNS

Show more

文字列のリスト

Comma-separated list of regular expressions defining uri paths that should be ignored (not measured).

Environment variable: QUARKUS_MICROMETER_BINDER_HTTP_CLIENT_IGNORE_PATTERNS

Show more

文字列のリスト

Suppress 4xx errors from metrics collection for unmatched templates. This configuration exists to limit cardinality explosion from caller side errors. Does not apply to 404 errors.

Suppressing 4xx errors is disabled by default.

Environment variable: QUARKUS_MICROMETER_BINDER_HTTP_CLIENT_SUPPRESS4XX_ERRORS

Show more

boolean

false

Maximum number of unique URI tag values allowed. After the max number of tag values is reached, metrics with additional tag values are denied by filter.

Environment variable: QUARKUS_MICROMETER_BINDER_HTTP_CLIENT_MAX_URI_TAGS

Show more

int

100

Comma-separated list of regular expressions used to specify uri labels in http metrics.

Vertx instrumentation will attempt to transform parameterized resource paths, /item/123, into a generic form, /item/{id}, to reduce the cardinality of uri label values.

Patterns specified here will take precedence over those computed values.

For example, if /item/\\\\d+=/item/custom or /item/[0-9]+=/item/custom is specified in this list, a request to a matching path (/item/123) will use the specified replacement value (/item/custom) as the value for the uri label. Note that backslashes must be double escaped as \\\\.

Environment variable: QUARKUS_MICROMETER_BINDER_HTTP_SERVER_MATCH_PATTERNS

Show more

文字列のリスト

Comma-separated list of regular expressions defining uri paths that should be ignored (not measured).

Environment variable: QUARKUS_MICROMETER_BINDER_HTTP_SERVER_IGNORE_PATTERNS

Show more

文字列のリスト

Suppress non-application uris from metrics collection. This will suppress all metrics for non-application endpoints using ${quarkus.http.root-path}/${quarkus.http.non-application-root-path}.

Suppressing non-application uris is enabled by default.

Environment variable: QUARKUS_MICROMETER_BINDER_HTTP_SERVER_SUPPRESS_NON_APPLICATION_URIS

Show more

boolean

true

Suppress 4xx errors from metrics collection for unmatched templates. This configuration exists to limit cardinality explosion from caller side error. Does not apply to 404 errors.

Suppressing 4xx errors is disabled by default.

Environment variable: QUARKUS_MICROMETER_BINDER_HTTP_SERVER_SUPPRESS4XX_ERRORS

Show more

boolean

false

Maximum number of unique URI tag values allowed. After the max number of tag values is reached, metrics with additional tag values are denied by filter.

Environment variable: QUARKUS_MICROMETER_BINDER_HTTP_SERVER_MAX_URI_TAGS

Show more

int

100

Prometheus registry configuration properties.

A property source for configuration of the Prometheus MeterRegistry, see https://micrometer.io/docs/registry/prometheus.

Environment variable: QUARKUS_MICROMETER_EXPORT_PROMETHEUS__CONFIGURATION_PROPERTY_NAME_

Show more

Map<String,String>

This property is deprecated: use quarkus.micrometer.binder.http-server.match-patterns.

Comma-separated list of regular expressions used to specify uri labels in http metrics.

Vertx instrumentation will attempt to transform parameterized resource paths, /item/123, into a generic form, /item/{id}, to reduce the cardinality of uri label values.

Patterns specified here will take precedence over those computed values.

For example, if /item/\\\\d+=/item/custom or /item/[0-9]+=/item/custom is specified in this list, a request to a matching path (/item/123) will use the specified replacement value (/item/custom) as the value for the uri label. Note that backslashes must be double escaped as \\\\.

Environment variable: QUARKUS_MICROMETER_BINDER_VERTX_MATCH_PATTERNS

Show more

文字列のリスト

This property is deprecated: use quarkus.micrometer.binder.http-server.ignore-patterns.

Comma-separated list of regular expressions defining uri paths that should be ignored (not measured).

Environment variable: QUARKUS_MICROMETER_BINDER_VERTX_IGNORE_PATTERNS

Show more

文字列のリスト

期間フォーマットについて

期間の値を書くには、標準の java.time.Duration フォーマットを使います。 詳細は Duration#parse() Java API documentation を参照してください。

数字で始まる簡略化した書式を使うこともできます:

  • 数値のみの場合は、秒単位の時間を表します。

  • 数値の後に ms が続く場合は、ミリ秒単位の時間を表します。

その他の場合は、簡略化されたフォーマットが解析のために java.time.Duration フォーマットに変換されます:

  • 数値の後に hms が続く場合は、その前に PT が付けられます。

  • 数値の後に d が続く場合は、その前に P が付けられます。

関連コンテンツ