Metriche di Micrometer per Java

SI APPLICA A: NoSQL

Java SDK per Azure Cosmos DB implementa le metriche client usando Micrometer per la strumentazione nei sistemi di osservabilità più diffusi, ad esempio Prometheus. Questo articolo include istruzioni e frammenti di codice per lo scorporo delle metriche in Prometheus, derivati da questo esempio. L'elenco completo delle metriche fornite dall'SDK è documentato qui. Se i client vengono distribuiti nel servizio Azure Kubernetes, è anche possibile usare il servizio gestito Monitoraggio di Azure per Prometheus con scorporo personalizzato. Per la documentazione, vedere qui.

Utilizzare le metriche da Prometheus

È possibile scaricare Prometheus da qui. Per usare le metriche di Micrometer in Java SDK per Azure Cosmos DB usando Prometheus, assicurarsi prima di tutto di aver importato le librerie necessarie per il registro e il client:

<dependency>
    <groupId>io.micrometer</groupId>
    <artifactId>micrometer-registry-prometheus</artifactId>
    <version>1.6.6</version>
</dependency>

<dependency>
    <groupId>io.prometheus</groupId>
    <artifactId>simpleclient_httpserver</artifactId>
    <version>0.5.0</version>
</dependency>

Nell'applicazione specificare il registro Prometheus per la configurazione dei dati di telemetria. Si noti che è possibile impostare varie soglie di diagnostica, che consentiranno di limitare le metriche utilizzate a quelle a cui si è più interessati:

//prometheus meter registry
PrometheusMeterRegistry prometheusRegistry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);

//provide the prometheus registry to the telemetry config
CosmosClientTelemetryConfig telemetryConfig = new CosmosClientTelemetryConfig()
        .diagnosticsThresholds(
                new CosmosDiagnosticsThresholds()
                        // Any requests that violate (are lower than) any of the below thresholds that are set
                        // will not appear in "request-level" metrics (those with "rntbd" or "gw" in their name).
                        // The "operation-level" metrics (those with "ops" in their name) will still be collected.
                        // Use this to reduce noise in the amount of metrics collected.
                        .setRequestChargeThreshold(10)
                        .setNonPointOperationLatencyThreshold(Duration.ofDays(10))
                        .setPointOperationLatencyThreshold(Duration.ofDays(10))
        )
        // Uncomment below to apply sampling to help further tune client-side resource consumption related to metrics.
        // The sampling rate can be modified after Azure Cosmos DB Client initialization – so the sampling rate can be
        // modified without any restarts being necessary.
        //.sampleDiagnostics(0.25)
        .clientCorrelationId("samplePrometheusMetrics001")
        .metricsOptions(new CosmosMicrometerMetricsOptions().meterRegistry(prometheusRegistry)
                //.configureDefaultTagNames(CosmosMetricTagName.PARTITION_KEY_RANGE_ID)
                .applyDiagnosticThresholdsForTransportLevelMeters(true)
        );

Avviare il server HttpServer locale per esporre le metriche del registro dei contatori a Prometheus:

try {
    HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
    server.createContext("/metrics", httpExchange -> {
        String response = prometheusRegistry.scrape();
        int i = 1;
        httpExchange.sendResponseHeaders(200, response.getBytes().length);
        try (OutputStream os = httpExchange.getResponseBody()) {
            os.write(response.getBytes());
        }
    });
    new Thread(server::start).start();
} catch (IOException e) {
    throw new RuntimeException(e);
}

Assicurarsi di passare clientTelemetryConfig durante la creazione di CosmosClient:

//  Create async client
client = new CosmosClientBuilder()
    .endpoint(AccountSettings.HOST)
    .key(AccountSettings.MASTER_KEY)
    .clientTelemetryConfig(telemetryConfig)
    .consistencyLevel(ConsistencyLevel.SESSION) //make sure we can read our own writes
    .contentResponseOnWriteEnabled(true)
    .buildAsyncClient();

Quando si aggiunge l'endpoint per il client dell'applicazione a prometheus.yml, aggiungere il nome di dominio e la porta a "targets". Ad esempio, se Prometheus è in esecuzione nello stesso server del client dell'app, è possibile aggiungere localhost:8080 a targets come indicato di seguito:

scrape_configs:
  # The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
  - job_name: "prometheus"

    # metrics_path defaults to '/metrics'
    # scheme defaults to 'http'.

    static_configs:
      - targets: ["localhost:9090", "localhost:8080"]

A questo punto è possibile utilizzare le metriche da Prometheus:

Screenshot of metrics graph in Prometheus explorer.

Passaggi successivi