Java 用 Azure Monitor クエリ クライアント ライブラリ - バージョン 1.2.6

Azure Monitor クエリ クライアント ライブラリは、 Azure Monitor の 2 つのデータ プラットフォームに対して読み取り専用クエリを実行するために使用されます。

  • ログ - 監視対象のリソースからログとパフォーマンス データを収集および整理します。 Azure サービスからのプラットフォーム ログ、仮想マシン エージェントからのログとパフォーマンス データ、アプリの使用状況とパフォーマンス データなど、さまざまなソースのデータを 1 つの Azure Log Analytics ワークスペースに統合できます。 さまざまなデータ型は、Kusto 照会言語を使用してまとめて分析できます。
  • メトリック - 監視対象のリソースから時系列データベースに数値データを収集します。 メトリックは、一定の間隔で収集される数値であり、特定の時刻におけるシステムの何らかの特性を表しています。 メトリックは軽量で、ほぼリアルタイムのシナリオをサポートできるため、アラートや問題の迅速な検出に特に役立ちます。

リソース:

作業の開始

前提条件

パッケージを組み込む

BOM ファイルを含める

ライブラリの一般提供 (GA) バージョンに依存するには、azure-sdk-bom をプロジェクトに含めてください。 次のスニペットでは、{bom_version_to_target} プレースホルダーをバージョン番号に置き換えます。 BOM の詳細については、 AZURE SDK BOM README に関するページを参照してください。

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.azure</groupId>
            <artifactId>azure-sdk-bom</artifactId>
            <version>{bom_version_to_target}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

次に、次に示すように、バージョン タグを使用せずに、依存関係セクションに直接依存関係を含めます。

<dependencies>
  <dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-monitor-query</artifactId>
  </dependency>
</dependencies>

直接依存関係を含める

BOM に存在しない特定のバージョンのライブラリに依存する場合は、次のように直接依存関係をプロジェクトに追加します。

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-monitor-query</artifactId>
    <version>1.2.6</version>
</dependency>

クライアントを作成する

ログまたはメトリックのクエリを実行するには、認証されたクライアントが必要です。 ライブラリには、クライアントの同期形式と非同期形式の両方が含まれています。 認証を行うために、次の例では azure-identity パッケージから を使用DefaultAzureCredentialBuilderします。

Azure Active Directory を使用した認証

Azure Id ライブラリを使用して、Azure Active Directory で認証できます。 リージョン エンドポイントは AAD 認証をサポートしないことに注意してください。 この種類の認証を使用するために、リソースのカスタム サブドメインを作成します。

次に示す DefaultAzureCredential プロバイダー、または Azure SDK で提供されている他の資格情報プロバイダーを使用するには、パッケージを azure-identity 含めてください。

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-identity</artifactId>
    <version>1.9.0</version>
</dependency>

AAD アプリケーションのクライアント ID、テナント ID、クライアント シークレットの値を環境変数として設定します(AZURE_CLIENT_ID、AZURE_TENANT_ID、AZURE_CLIENT_SECRET)。

同期クライアント

LogsQueryClient logsQueryClient = new LogsQueryClientBuilder()
    .credential(new DefaultAzureCredentialBuilder().build())
    .buildClient();
MetricsQueryClient metricsQueryClient = new MetricsQueryClientBuilder()
    .credential(new DefaultAzureCredentialBuilder().build())
    .buildClient();

非同期クライアント

LogsQueryAsyncClient logsQueryAsyncClient = new LogsQueryClientBuilder()
    .credential(new DefaultAzureCredentialBuilder().build())
    .buildAsyncClient();
MetricsQueryAsyncClient metricsQueryAsyncClient = new MetricsQueryClientBuilder()
    .credential(new DefaultAzureCredentialBuilder().build())
    .buildAsyncClient();

非パブリック Azure クラウドのクライアントを構成する

既定では、 LogQueryClientMetricQueryClient は、パブリック Azure Cloud に接続するように構成されています。 これらは、クライアント ビルダーで 正しい endpoint を設定することで、非パブリック Azure クラウドに接続するように構成できます。次に例を示します。

Azure China クラウド用の を LogsQueryClient 作成する:

LogsQueryClient logsQueryClient = new LogsQueryClientBuilder()
    .credential(new DefaultAzureCredentialBuilder().build())
    .endpoint("https://api.loganalytics.azure.cn/v1")
    .buildClient();

Azure China クラウド用の を MetricsQueryClient 作成する:

MetricsQueryClient metricsQueryClient = new MetricsQueryClientBuilder()
    .credential(new DefaultAzureCredentialBuilder().build())
    .endpoint("https://management.chinacloudapi.cn")
    .buildClient();

クエリを実行します

ログクエリとメトリッククエリの例については、「例」セクション 参照してください。

主要な概念

クエリ レートの制限と調整をログに記録する

Log Analytics サービスは、要求レートが高すぎる場合に調整を適用します。 返される行の最大数などの制限は、Kusto クエリにも適用されます。 詳細については、「 クエリ API」を参照してください。

メトリック データ構造

メトリック値の各セットは、次の特性を持つ時系列です。

  • 値が収集された時刻
  • 値に関連付けられているリソース
  • メトリックのカテゴリのように機能する名前空間
  • メトリック名
  • 値そのもの
  • 多次元メトリックで説明されているように、一部のメトリックには複数のディメンションが含まれる場合があります。 カスタム メトリックは最大 10 個のディメンションを持つことができます。

Logs クエリ

LogsQueryClient logsQueryClient = new LogsQueryClientBuilder()
        .credential(new DefaultAzureCredentialBuilder().build())
        .buildClient();

LogsQueryResult queryResults = logsQueryClient.queryWorkspace("{workspace-id}", "{kusto-query}",
        new QueryTimeInterval(Duration.ofDays(2)));

for (LogsTableRow row : queryResults.getTable().getRows()) {
    System.out.println(row.getColumnValue("OperationName") + " " + row.getColumnValue("ResourceGroup"));
}

ログのクエリ結果をモデルにマップする

public class CustomLogModel {
    private String resourceGroup;
    private String operationName;

    public String getResourceGroup() {
        return resourceGroup;
    }

    public String getOperationName() {
        return operationName;
    }
}
LogsQueryClient logsQueryClient = new LogsQueryClientBuilder()
        .credential(new DefaultAzureCredentialBuilder().build())
        .buildClient();

List<CustomLogModel> customLogModels = logsQueryClient.queryWorkspace("{workspace-id}", "{kusto-query}",
        new QueryTimeInterval(Duration.ofDays(2)), CustomLogModel.class);

for (CustomLogModel customLogModel : customLogModels) {
    System.out.println(customLogModel.getOperationName() + " " + customLogModel.getResourceGroup());
}

ログのクエリ応答を処理する

API は queryLogsQueryResult返し、API は queryBatch を返します LogsBatchQueryResult。 応答の階層を次に示します。

LogsQueryResult / LogsBatchQueryResult
|---id (this exists in `LogsBatchQueryResult` object only)
|---status (this exists in `LogsBatchQueryResult` object only)
|---statistics
|---visualization
|---error
|---tables (list of `LogsTable` objects)
    |---name
    |---rows (list of `LogsTableRow` objects)
        |--- rowIndex
        |--- rowCells (list of `LogsTableCell` objects)
    |---columns (list of `LogsTableColumn` objects)
        |---name
        |---type

リソース ID でログを照会する

ではLogsQueryClient、ワークスペース ID ( メソッド) またはリソース ID (queryWorkspacequeryResource メソッド) を使用したログのクエリがサポートされています。 リソース ID を使用してログのクエリを実行する例を次に示します。 同様の変更は、他のすべてのサンプルに適用できます。

LogsQueryClient logsQueryClient = new LogsQueryClientBuilder()
    .credential(new DefaultAzureCredentialBuilder().build())
    .buildClient();

LogsQueryResult queryResults = logsQueryClient.queryResource("{resource-id}", "{kusto-query}",
    new QueryTimeInterval(Duration.ofDays(2)));

for (LogsTableRow row : queryResults.getTable().getRows()) {
    System.out.println(row.getColumnValue("OperationName") + " " + row.getColumnValue("ResourceGroup"));
}

バッチ ログ クエリ

LogsQueryClient logsQueryClient = new LogsQueryClientBuilder()
        .credential(new DefaultAzureCredentialBuilder().build())
        .buildClient();

LogsBatchQuery logsBatchQuery = new LogsBatchQuery();
String query1 = logsBatchQuery.addWorkspaceQuery("{workspace-id}", "{query-1}", new QueryTimeInterval(Duration.ofDays(2)));
String query2 = logsBatchQuery.addWorkspaceQuery("{workspace-id}", "{query-2}", new QueryTimeInterval(Duration.ofDays(30)));
String query3 = logsBatchQuery.addWorkspaceQuery("{workspace-id}", "{query-3}", new QueryTimeInterval(Duration.ofDays(10)));

LogsBatchQueryResultCollection batchResults = logsQueryClient
        .queryBatchWithResponse(logsBatchQuery, Context.NONE).getValue();

LogsBatchQueryResult query1Result = batchResults.getResult(query1);
for (LogsTableRow row : query1Result.getTable().getRows()) {
    System.out.println(row.getColumnValue("OperationName") + " " + row.getColumnValue("ResourceGroup"));
}

List<CustomLogModel> customLogModels = batchResults.getResult(query2, CustomLogModel.class);
for (CustomLogModel customLogModel : customLogModels) {
    System.out.println(customLogModel.getOperationName() + " " + customLogModel.getResourceGroup());
}

LogsBatchQueryResult query3Result = batchResults.getResult(query3);
if (query3Result.getQueryResultStatus() == LogsQueryResultStatus.FAILURE) {
    System.out.println(query3Result.getError().getMessage());
}

高度なログクエリシナリオ

ログクエリのタイムアウトを設定する

LogsQueryClient logsQueryClient = new LogsQueryClientBuilder()
    .credential(new DefaultAzureCredentialBuilder().build())
    .buildClient();

// set request options: server timeout
LogsQueryOptions options = new LogsQueryOptions()
    .setServerTimeout(Duration.ofMinutes(10));

Response<LogsQueryResult> response = logsQueryClient.queryWorkspaceWithResponse("{workspace-id}",
        "{kusto-query}", new QueryTimeInterval(Duration.ofDays(2)), options, Context.NONE);

複数のワークスペースにクエリを実行する

複数の Log Analytics ワークスペースに対して同じクエリを実行するには、 メソッドを LogsQueryOptions.setAdditionalWorkspaces 使用します。

クエリに複数のワークスペースが含まれている場合、結果テーブルのログは、取得元のワークスペースに従ってグループ化されません。 結果テーブル内の行のワークスペースを識別するには、結果テーブルの "TenantId" 列を調べることができます。 この列がテーブルにない場合は、クエリ文字列を更新してこの列を含める必要がある場合があります。

LogsQueryClient logsQueryClient = new LogsQueryClientBuilder()
        .credential(new DefaultAzureCredentialBuilder().build())
        .buildClient();

Response<LogsQueryResult> response = logsQueryClient.queryWorkspaceWithResponse("{workspace-id}", "{kusto-query}",
        new QueryTimeInterval(Duration.ofDays(2)), new LogsQueryOptions()
                .setAdditionalWorkspaces(Arrays.asList("{additional-workspace-identifiers}")),
        Context.NONE);
LogsQueryResult result = response.getValue();

統計情報を含める

CPU やメモリ消費量などのログ クエリ実行統計を取得するには、次のようにします。

  1. を に設定setIncludeStatistics()して、応答の統計を要求するには、 を使用LogsQueryOptionsしますtrue
  2. オブジェクトで getStatistics メソッドを LogsQueryResult 呼び出します。

次の例では、クエリの実行時間を出力します。

LogsQueryClient client = new LogsQueryClientBuilder()
        .credential(credential)
        .buildClient();

LogsQueryOptions options = new LogsQueryOptions()
        .setIncludeStatistics(true);
Response<LogsQueryResult> response = client.queryWorkspaceWithResponse("{workspace-id}",
        "AzureActivity | top 10 by TimeGenerated", QueryTimeInterval.LAST_1_HOUR, options, Context.NONE);
LogsQueryResult result = response.getValue();
BinaryData statistics = result.getStatistics();

ObjectMapper objectMapper = new ObjectMapper();
JsonNode statisticsJson = objectMapper.readTree(statistics.toBytes());
JsonNode queryStatistics = statisticsJson.get("query");
System.out.println("Query execution time = " + queryStatistics.get("executionTime").asDouble());

統計ペイロードの構造はクエリによって異なるため、戻り値の BinaryData 型が使用されます。 生の JSON 応答が含まれています。 統計は、JSON の query プロパティ内にあります。 次に例を示します。

{
  "query": {
    "executionTime": 0.0156478,
    "resourceUsage": {...},
    "inputDatasetStatistics": {...},
    "datasetStatistics": [{...}]
  }
}

視覚化を含める

render 演算子を使用してログ クエリの視覚化データを取得するには:

  1. を に設定setIncludeVisualization()して、応答内の視覚化データを要求するには、 を使用LogsQueryOptionsしますtrue
  2. オブジェクトで getVisualization メソッドを LogsQueryResult 呼び出します。

次に例を示します。

LogsQueryClient client = new LogsQueryClientBuilder()
        .credential(credential)
        .buildClient();

String visualizationQuery = "StormEvents"
        + "| summarize event_count = count() by State"
        + "| where event_count > 10"
        + "| project State, event_count"
        + "| render columnchart";
LogsQueryOptions options = new LogsQueryOptions()
        .setIncludeVisualization(true);
Response<LogsQueryResult> response = client.queryWorkspaceWithResponse("{workspace-id}", visualizationQuery,
        QueryTimeInterval.LAST_7_DAYS, options, Context.NONE);
LogsQueryResult result = response.getValue();
BinaryData visualization = result.getVisualization();

ObjectMapper objectMapper = new ObjectMapper();
JsonNode visualizationJson = objectMapper.readTree(visualization.toBytes());
System.out.println("Visualization graph type = " + visualizationJson.get("visualization").asText());

視覚化ペイロードの構造はクエリによって異なるため、戻り値の BinaryData 型が使用されます。 生の JSON 応答が含まれています。 次に例を示します。

{
  "visualization": "columnchart",
  "title": null,
  "accumulate": false,
  "isQuerySorted": false,
  "kind": null,
  "legend": null,
  "series": null,
  "yMin": "",
  "yMax": "",
  "xAxis": null,
  "xColumn": null,
  "xTitle": null,
  "yAxis": null,
  "yColumns": null,
  "ySplit": null,
  "yTitle": null,
  "anomalyColumns": null
}

メトリック クエリ

メトリックのクエリを実行するには、次のサンプルの {resource-id} プレースホルダーで示されるリソース ID が必要です。 リソース ID を見つけるには、次のようにします。

  1. Azure portalでリソースのページに移動します。
  2. [ 概要 ] ブレードで、[ JSON ビュー ] リンクを選択します。
  3. 結果の JSON で、 プロパティの値を id コピーします。
MetricsQueryClient metricsQueryClient = new MetricsQueryClientBuilder()
        .credential(new DefaultAzureCredentialBuilder().build())
        .buildClient();

MetricsQueryResult metricsQueryResult = metricsQueryClient.queryResource("{resource-uri}",
        Arrays.asList("SuccessfulCalls", "TotalCalls"));

for (MetricResult metric : metricsQueryResult.getMetrics()) {
    System.out.println("Metric name " + metric.getMetricName());
    for (TimeSeriesElement timeSeriesElement : metric.getTimeSeries()) {
        System.out.println("Dimensions " + timeSeriesElement.getMetadata());
        for (MetricValue metricValue : timeSeriesElement.getValues()) {
            System.out.println(metricValue.getTimeStamp() + " " + metricValue.getTotal());
        }
    }
}

メトリック クエリの応答を処理する

メトリック クエリ API は オブジェクトを MetricsQueryResult 返します。 MetricsQueryResultオブジェクトには、型指定されたオブジェクト、、、granularitynamespaceおよび timeIntervalMetricResult一覧などのプロパティが含まれています。 オブジェクトの一覧には MetricResult 、 パラメーターを metrics 使用してアクセスできます。 この一覧の各 MetricResult オブジェクトには、オブジェクトの TimeSeriesElement 一覧が含まれています。 それぞれに TimeSeriesElement と プロパティがmetadata_valuesdata含まれています。 ビジュアル形式では、応答のオブジェクト階層は次の構造のようになります。

MetricsQueryResult
|---granularity
|---timeInterval
|---cost
|---namespace
|---resourceRegion
|---metrics (list of `MetricResult` objects)
    |---id
    |---type
    |---name
    |---unit
    |---timeSeries (list of `TimeSeriesElement` objects)
        |---metadata (dimensions)
        |---metricValues (list of data points represented by `MetricValue` objects)
             |--- timeStamp
             |--- count
             |--- average
             |--- total
             |--- maximum
             |--- minimum

平均メトリックとカウント メトリックを取得する

MetricsQueryClient metricsQueryClient = new MetricsQueryClientBuilder()
    .credential(new DefaultAzureCredentialBuilder().build())
    .buildClient();

Response<MetricsQueryResult> metricsResponse = metricsQueryClient
    .queryResourceWithResponse("{resource-id}", Arrays.asList("SuccessfulCalls", "TotalCalls"),
        new MetricsQueryOptions()
            .setGranularity(Duration.ofHours(1))
            .setAggregations(Arrays.asList(AggregationType.AVERAGE, AggregationType.COUNT)),
        Context.NONE);

MetricsQueryResult metricsQueryResult = metricsResponse.getValue();

for (MetricResult metric : metricsQueryResult.getMetrics()) {
    System.out.println("Metric name " + metric.getMetricName());
    for (TimeSeriesElement timeSeriesElement : metric.getTimeSeries()) {
        System.out.println("Dimensions " + timeSeriesElement.getMetadata());
        for (MetricValue metricValue : timeSeriesElement.getValues()) {
            System.out.println(metricValue.getTimeStamp() + " " + metricValue.getTotal());
        }
    }
}

トラブルシューティング

さまざまな障害シナリオを診断する方法の詳細については、 トラブルシューティング ガイド を参照してください。

次の手順

Azure Monitor の詳細については、 Azure Monitor サービスのドキュメントを参照してください

共同作成

このプロジェクトでは、共同作成と提案を歓迎しています。 ほとんどの共同作成では、共同作成者使用許諾契約書 (CLA) にご同意いただき、ご自身の共同作成内容を使用する権利を Microsoft に供与する権利をお持ちであり、かつ実際に供与することを宣言していただく必要があります。

pull request を送信すると、CLA を提供して PR (ラベル、コメントなど) を適宜装飾する必要があるかどうかを CLA ボットが自動的に決定します。 ボットによって提供される手順にそのまま従ってください。 この操作は、Microsoft の CLA を使用するすべてのリポジトリについて、1 回だけ行う必要があります。

このプロジェクトでは、Microsoft オープン ソースの倫理規定を採用しています。 詳細については、倫理規定についてよくあるご質問を参照するか、opencode@microsoft.com 宛てにご質問またはコメントをお送りください。

インプレッション数