The English version of quarkus.io is the official project site. Translated sites are community supported on a best-effort basis.
このページを編集

Micrometer メトリクス

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

このドキュメントは、オブザーバビリティコンポーネントとその他のオブザーバビリティ関連コンポーネントを取り上げている Quarkus のオブザーバビリティリファレンスガイド の一部です。

Micrometerは、Quarkusのメトリクスとして推奨されるアプローチです。
デフォルトでは、メトリクスはメイン HTTP サーバーで公開されます。 別の管理ポートからメトリクスを表示する場合は、Managed interface セクションを参照してください。

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

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

Quarkus エクステンション:

  • micrometer

  • micrometer-registry-prometheus

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コアライブラリが依存ライブラリとして追加されます。

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

コマンドラインインタフェース
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 エクステンションを使用します。

コマンドラインインタフェース
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 を設定して初期化するために、独自のプロバイダを指定する必要があります。

カスタマイズされた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 を返します。

この例は、Micrometer ドキュメントの Micrometer StatsD: Customizing the Metrics Sink の手順に対応しています。

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

独自のメトリクスの作成

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

メトリクスは遅延して構築されます。エンドポイントへのアクセスなど、メトリクスを作成するアクションを実行するまで、探しているメトリクスのデータが表示されない場合があります。

命名規則

メーター名では、ドットを使用してセグメントを区切る必要があります (例: 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のドキュメントを参照してください。

メトリクス名とディメンションの一意の組み合わせごとに、一意の時系列が生成されます。 無制限のディメンションデータセットを使用すると、「カーディナリティーの爆発」、つまり新しい時系列の作成が指数関数的に増加する可能性があります。

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 は、デフォルトでは監視対象のオブジェクトに対して強い参照を作成しません。 レジストリーによっては、Micrometer はガベージコレクションが設定されたオブジェクトを監視するゲージを完全に省略するか、 監視値として NaN (not a number) を使用します。

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

カウンター

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

  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 パーセンタイルなど)。

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

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/[0-9]+=/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/ ) に指定することで、以前のフォーマットに戻すことも可能です。

Micrometer のカスタマイズ

Quarkus provides a variety of way to customize Micrometer.

MeterFilter を使用して、発行されるタグとメトリクスをカスタマイズします。

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;
            }
        };
    }
}

この例では、シングルトン CDI Beanは、2 つの異なる MeterFilter Beanを生成します。1 つは Prometheus MeterRegistry インスタンスのみに適用され ( @MeterFilterConstraint 修飾子を使用)、もう 1 つはすべての MeterRegistry インスタンスに適用されます。アプリケーション設定プロパティーも注入され、タグ値として使用されます。MeterFiltersのその他の例は、次のリンクにあります:公式ドキュメント

サーバーの HTTP リクエストに HttpServerMetricsTagsContributor を使用する

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

このインターフェイスを使用してタグを作成する場合、値のカーディナリティーを制限することが重要です。制限しない場合、メトリクスシステムの容量が大幅に低下するリスクがあります。

クライアントの HTTP リクエストには HttpClientMetricsTagsContributor を使用する

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

メーターレジストリーを任意にカスタマイズする MeterRegistryCustomizer の使用

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) { ... }
提供されるタグ値は、低いカーディナリティーである必要があります。 カーディナリティー値が高いと、メトリクスのバックエンドでパフォーマンスとストレージの問題が発生する可能性があります (「カーディナリティーの爆発」)。 タグ値にはエンドユーザーデータは使用しないでください。これらは、カーディナリティーが高い可能性があるためです。

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

MicroProfile Metrics API のサポート

アプリケーションで MicroProfile Metrics API を使用する場合、 Micrometer エクステンションは、これらのメトリクスを Micrometer レジストリーにマッピングするための適応レイヤーを作成します。 2 つのシステム間の命名規則が異なるため、Micrometer で MP Metrics を使用する際に生成されるメトリクスが変わることに注意してください。

Use a MeterFilter to remap names or tags according to your conventions.

@Produces
@Singleton
public MeterFilter renameApplicationMeters() {
    final String targetMetric = MPResourceClass.class.getName() + ".mpAnnotatedMethodName";

    return MeterFilter() {
        @Override
        public Meter.Id map(Meter.Id id) {
            if (id.getName().equals(targetMetric)) {
                // Drop the scope tag (MP Registry type: application, vendor, base)
                List<Tag> tags = id.getTags().stream().filter(x -> !"scope".equals(x.getKey()))
                        .collect(Collectors.toList());
                // rename the metric
                return id.withName("my.metric.name").replaceTags(tags);
            }
            return id;
        }
    };
}

MicroProfile Metrics API が必要な場合は、次の依存関係が存在することを確認してください。

pom.xml
<dependency>
    <groupId>org.eclipse.microprofile.metrics</groupId>
    <artifactId>microprofile-metrics-api</artifactId>
</dependency>
build.gradle
implementation("org.eclipse.microprofile.metrics:microprofile-metrics-api")
MP Metrics API 互換性レイヤーは、将来的に別のエクステンションに移動される可能性があります。

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

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 # Enable json metrics
quarkus.micrometer.export.json.path=metrics/json
quarkus.micrometer.export.prometheus.path=metrics/prometheus

このような設定にすることで、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.

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

Environment variable: QUARKUS_MICROMETER_BINDER_ENABLED_DEFAULT

Show more

boolean

true

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

Eclipse MicroProfile Metrics support.

Support for MicroProfile Metrics will be enabled if Micrometer support is enabled and the MicroProfile Metrics dependency is present:

<dependency>
  <groupId>org.eclipse.microprofile.metrics</groupId>
  <artifactId>microprofile-metrics-api</artifactId>
</dependency>

The Micrometer extension currently provides a compatibility layer that supports the MP Metrics API, but metric names and recorded values will be different. Note that the MP Metrics compatibility layer will move to a different extension in the future.

Environment variable: QUARKUS_MICROMETER_BINDER_MP_METRICS_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

list of string

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

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.

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

list of string

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

list of string

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>

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

list of string

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

list of string

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

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

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

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

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

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

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

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

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

関連コンテンツ