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

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

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

リソース:

作業の開始

前提条件

パッケージをインストールする

pip を使用して Python 用 Azure Monitor クエリ クライアント ライブラリをインストールします。

pip install azure-monitor-query

クライアントを作成する

ログまたはメトリックに対してクエリを実行するには、認証されたクライアントが必要です。 ライブラリには、クライアントの同期形式と非同期形式の両方が含まれています。 認証するには、トークン資格情報のインスタンスを作成します。 または MetricsQueryClientを作成するときに、そのインスタンスをLogsQueryClient使用します。 次の例では、azure-identity パッケージから を使用DefaultAzureCredentialします。

同期クライアント

ログとメトリックの両方のクエリに同期クライアントを作成する次の例を考えてみましょう。

from azure.identity import DefaultAzureCredential
from azure.monitor.query import LogsQueryClient, MetricsQueryClient

credential = DefaultAzureCredential()
logs_client = LogsQueryClient(credential)
metrics_client = MetricsQueryClient(credential)

非同期クライアント

クエリ クライアント API の非同期形式は、サフィックス付き名前空間にあります .aio。 例:

from azure.identity.aio import DefaultAzureCredential
from azure.monitor.query.aio import LogsQueryClient, MetricsQueryClient

credential = DefaultAzureCredential()
async_logs_client = LogsQueryClient(credential)
async_metrics_client = MetricsQueryClient(credential)

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

既定では、 LogsQueryClientMetricsQueryClient は、パブリック Azure クラウドに接続するように構成されています。 これらは、正しい endpoint 引数を渡すことによって、非パブリック Azure クラウドに接続するように構成できます。次に例を示します。

logs_client = LogsQueryClient(credential, endpoint="https://api.loganalytics.azure.cn/v1")
metrics_client = MetricsQueryClient(credential, endpoint="https://management.chinacloudapi.cn")

: 現時点では、MetricsQueryClientメトリックのクエリに Azure Resource Manager (ARM) エンドポイントを使用しているため、このクライアントを使用する場合は、クラウドに対応する管理エンドポイントが必要になります。 これは将来変更される可能性があります。

クエリを実行します

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

主要な概念

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

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

バッチ ログ クエリを実行している場合、調整された要求は オブジェクトを LogsQueryError 返します。 そのオブジェクトの code 値は になります ThrottledError

メトリック データ構造

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

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

Logs クエリ

この例では、Log Analytics ワークスペースに対してクエリを実行する方法を示します。 応答を処理して表形式で表示するには、 pandas ライブラリが使用されます。 pandas を使用しないことを選択した場合は、 サンプル を参照してください。

期間を指定する

パラメーターは timespan 、データのクエリを実行する期間を指定します。 この値は、次のいずれかです。

  • a timedelta
  • timedelta 開始 datetime
  • 開始 datetime/end datetime

例:

import os
import pandas as pd
from datetime import datetime, timezone
from azure.monitor.query import LogsQueryClient, LogsQueryStatus
from azure.identity import DefaultAzureCredential
from azure.core.exceptions import HttpResponseError

credential = DefaultAzureCredential()
client = LogsQueryClient(credential)

query = """AppRequests | take 5"""

start_time=datetime(2021, 7, 2, tzinfo=timezone.utc)
end_time=datetime(2021, 7, 4, tzinfo=timezone.utc)

try:
    response = client.query_workspace(
        workspace_id=os.environ['LOG_WORKSPACE_ID'],
        query=query,
        timespan=(start_time, end_time)
        )
    if response.status == LogsQueryStatus.PARTIAL:
        error = response.partial_error
        data = response.partial_data
        print(error)
    elif response.status == LogsQueryStatus.SUCCESS:
        data = response.tables
    for table in data:
        df = pd.DataFrame(data=table.rows, columns=table.columns)
        print(df)
except HttpResponseError as err:
    print("something fatal happened")
    print(err)

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

API はquery_workspace、 または オブジェクトをLogsQueryResultLogsQueryPartialResult返します。 API はbatch_query、および オブジェクトを含むLogsQueryResultLogsQueryPartialResult可能性があるリストをLogsQueryError返します。 応答の階層を次に示します。

LogsQueryResult
|---statistics
|---visualization
|---tables (list of `LogsTable` objects)
    |---name
    |---rows
    |---columns
    |---columns_types

LogsQueryPartialResult
|---statistics
|---visualization
|---partial_error (a `LogsQueryError` object)
    |---code
    |---message
    |---details
    |---status
|---partial_data (list of `LogsTable` objects)
    |---name
    |---rows
    |---columns
    |---columns_types

LogsQueryResult 、便宜上テーブルを直接反復処理します。 たとえば、テーブルを使用してログ クエリ応答を処理し、pandas を使用して表示するには、次のようにします。

response = client.query(...)
for table in response:
    df = pd.DataFrame(table.rows, columns=[col.name for col in table.columns])

完全なサンプル については、こちらを参照してください

同様の方法で、バッチ ログクエリ応答を処理するには:

for result in response:
    if result.status == LogsQueryStatus.SUCCESS:
        for table in result:
            df = pd.DataFrame(table.rows, columns=table.columns)
            print(df)

完全なサンプル については、こちらを参照してください

バッチ ログ クエリ

次の例では、バッチ クエリ API を使用して複数のクエリを同時に送信する方法を示します。 クエリは、オブジェクトまたはディクショナリの LogsBatchQuery 一覧として表すことができます。 この例では、前者のアプローチを使用します。

import os
from datetime import timedelta, datetime, timezone
import pandas as pd
from azure.monitor.query import LogsQueryClient, LogsBatchQuery, LogsQueryStatus
from azure.identity import DefaultAzureCredential

credential = DefaultAzureCredential()
client = LogsQueryClient(credential)
requests = [
    LogsBatchQuery(
        query="AzureActivity | summarize count()",
        timespan=timedelta(hours=1),
        workspace_id=os.environ['LOG_WORKSPACE_ID']
    ),
    LogsBatchQuery(
        query= """bad query""",
        timespan=timedelta(days=1),
        workspace_id=os.environ['LOG_WORKSPACE_ID']
    ),
    LogsBatchQuery(
        query= """let Weight = 92233720368547758;
        range x from 1 to 3 step 1
        | summarize percentilesw(x, Weight * 100, 50)""",
        workspace_id=os.environ['LOG_WORKSPACE_ID'],
        timespan=(datetime(2021, 6, 2, tzinfo=timezone.utc), datetime(2021, 6, 5, tzinfo=timezone.utc)), # (start, end)
        include_statistics=True
    ),
]
results = client.query_batch(requests)

for res in results:
    if res.status == LogsQueryStatus.FAILURE:
        # this will be a LogsQueryError
        print(res.message)
    elif res.status == LogsQueryStatus.PARTIAL:
        ## this will be a LogsQueryPartialResult
        print(res.partial_error)
        for table in res.partial_data:
            df = pd.DataFrame(table.rows, columns=table.columns)
            print(df)
    elif res.status == LogsQueryStatus.SUCCESS:
        ## this will be a LogsQueryResult
        table = res.tables[0]
        df = pd.DataFrame(table.rows, columns=table.columns)
        print(df)

リソース ログクエリ

次の例では、Log Analytics ワークスペースを使用せずに、Azure リソースからログに直接クエリを実行する方法を示します。 ここでは、 query_resource メソッドが の代わりに query_workspace使用され、ワークスペース ID の代わりに Azure リソース識別子が渡されます (例: /subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider}/{resource-type}/{resource-name})。

import os
import pandas as pd
from datetime import timedelta
from azure.monitor.query import LogsQueryClient, LogsQueryStatus
from azure.core.exceptions import HttpResponseError
from azure.identity import DefaultAzureCredential

credential  = DefaultAzureCredential()
client = LogsQueryClient(credential)

query = """AzureActivity | take 5"""

try:
    response = client.query_resource(os.environ['LOGS_RESOURCE_ID'], query, timespan=timedelta(days=1))
    if response.status == LogsQueryStatus.PARTIAL:
        error = response.partial_error
        data = response.partial_data
        print(error)
    elif response.status == LogsQueryStatus.SUCCESS:
        data = response.tables
    for table in data:
        df = pd.DataFrame(data=table.rows, columns=table.columns)
        print(df)
except HttpResponseError as err:
    print("something fatal happened")
    print(err)

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

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

次の例は、サーバータイムアウトを秒単位で設定する方法を示しています。 クエリに前述のタイムアウトよりも多くの時間がかかる場合、ゲートウェイ タイムアウトが発生します。 既定値は 180 秒で、最大 10 分 (600 秒) に設定できます。

import os
from azure.monitor.query import LogsQueryClient
from azure.identity import DefaultAzureCredential

credential = DefaultAzureCredential()
client = LogsQueryClient(credential)

response = client.query_workspace(
    os.environ['LOG_WORKSPACE_ID'],
    "range x from 1 to 10000000000 step 1 | count",
    timespan=timedelta(days=1),
    server_timeout=600 # sets the timeout to 10 minutes
    )

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

同じログ クエリを複数の Log Analytics ワークスペースで実行できます。 Kusto クエリに加えて、次のパラメーターが必要です。

  • workspace_id - 最初の (プライマリ) ワークスペース ID。
  • additional_workspaces - パラメーターで指定されたワークスペースを除くワークスペースの workspace_id 一覧。 パラメーターのリスト アイテムは、次の識別子形式で構成される場合があります。
    • 修飾されたワークスペース名
    • ワークスペース ID
    • Azure リソース ID

たとえば、次のクエリは 3 つのワークスペースで実行されます。

client.query_workspace(
    <workspace_id>,
    query,
    timespan=timedelta(days=1),
    additional_workspaces=['<workspace 2>', '<workspace 3>']
    )

完全なサンプル については、こちらを参照してください

統計情報を含める

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

  1. include_statistics パラメーターを True に設定します。
  2. オブジェクト内の statistics フィールドに LogsQueryResult アクセスします。

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

query = "AzureActivity | top 10 by TimeGenerated"
result = client.query_workspace(
    <workspace_id>,
    query,
    timespan=timedelta(days=1),
    include_statistics=True
    )

execution_time = result.statistics.get("query", {}).get("executionTime")
print(f"Query execution time: {execution_time}")

フィールドはstatisticsdict生の JSON 応答に対応する であり、その構造はクエリによって異なる場合があります。 統計は プロパティ内にあります query 。 次に例を示します。

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

視覚化を含める

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

  1. include_visualization プロパティを Trueに設定します。
  2. オブジェクト内の visualization フィールドに LogsQueryResult アクセスします。

次に例を示します。

query = (
    "StormEvents"
    "| summarize event_count = count() by State"
    "| where event_count > 10"
    "| project State, event_count"
    "| render columnchart"
)
result = client.query_workspace(
    <workspace_id>,
    query,
    timespan=timedelta(days=1),
    include_visualization=True
    )

print(f"Visualization result: {result.visualization}")

フィールドはvisualizationdict生の JSON 応答に対応する であり、その構造はクエリによって異なる場合があります。 例:

{
  "visualization": "columnchart",
  "title": "the chart title",
  "accumulate": False,
  "isQuerySorted": False,
  "kind": None,
  "legend": None,
  "series": None,
  "yMin": "NaN",
  "yMax": "NaN",
  "xAxis": None,
  "xColumn": None,
  "xTitle": "x axis title",
  "yAxis": None,
  "yColumns": None,
  "ySplit": None,
  "yTitle": None,
  "anomalyColumns": None
}

メトリック クエリ

次の例では、Event Grid サブスクリプションのメトリックを取得します。 リソース URI は、Event Grid トピックの URI です。

リソース URI は、メトリックのクエリ対象のリソースの URI である必要があります。 これは通常、 という形式 /subscriptions/<id>/resourceGroups/<rg-name>/providers/<source>/topics/<resource-name>です。

リソース URI を見つけるには:

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

: メトリックは、送信されたmetric_namesの順序で返されます。

import os
from datetime import timedelta, datetime
from azure.monitor.query import MetricsQueryClient
from azure.identity import DefaultAzureCredential

credential = DefaultAzureCredential()
client = MetricsQueryClient(credential)
start_time = datetime(2021, 5, 25)
duration = timedelta(days=1)
metrics_uri = os.environ['METRICS_RESOURCE_URI']
response = client.query_resource(
    metrics_uri,
    metric_names=["PublishSuccessCount"],
    timespan=(start_time, duration)
    )

for metric in response.metrics:
    print(metric.name)
    for time_series_element in metric.timeseries:
        for metric_value in time_series_element.data:
            print(metric_value.time_stamp)

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

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

MetricsQueryResult
|---granularity
|---timespan
|---cost
|---namespace
|---resource_region
|---metrics (list of `Metric` objects)
    |---id
    |---type
    |---name
    |---unit
    |---timeseries (list of `TimeSeriesElement` objects)
        |---metadata_values
        |---data (list of data points represented by `MetricValue` objects)

応答の処理例

import os
from azure.monitor.query import MetricsQueryClient, MetricAggregationType
from azure.identity import DefaultAzureCredential

credential = DefaultAzureCredential()
client = MetricsQueryClient(credential)

metrics_uri = os.environ['METRICS_RESOURCE_URI']
response = client.query_resource(
    metrics_uri,
    metric_names=["MatchedEventCount"],
    aggregations=[MetricAggregationType.COUNT]
    )

for metric in response.metrics:
    print(metric.name)
    for time_series_element in metric.timeseries:
        for metric_value in time_series_element.data:
            if metric_value.count != 0:
                print(
                    "There are {} matched events at {}".format(
                        metric_value.count,
                        metric_value.time_stamp
                    )
                )

トラブルシューティング

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

次のステップ

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

サンプル

次のコード サンプルは、Azure Monitor クエリ クライアント ライブラリの一般的なシナリオを示しています。

ログ クエリのサンプル

メトリック クエリのサンプル

共同作成

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

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

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