LoginSignup
1
0

pythonでAzure MonitorのLog Analyticsにクエリを実行してログを取得するサンプル

Posted at

概要

環境

pipenv を使った python3.11 で確認

事前準備

  • 取得する Log Analytics ワークスペースの ワークスペースID を控えておく
    image.png

ライブラリ

[packages]
azure-loganalytics = "*"
azure-monitor-query = "*"
azure-identity = "*"
pandas = "*"
  • pip などでインストール

サンプルコード

コメント部分を修正して実行する

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

# Azure CLI で az login した認証情報を使う
credential = AzureCliCredential()  # DefaultAzureCredential()
client = LogsQueryClient(credential)

# 発行するクエリを指定
query = "AppServiceConsoleLogs | where _ResourceId contains 'xxxxxxx'"

# ワークスペースID を指定
LOG_WORKSPACE_ID = "xxxx-xx-xx-xxx-x"

# 取得期間を指定
start_time = datetime(2023, 4, 1, tzinfo=timezone.utc)
end_time = datetime(2023, 10, 1, tzinfo=timezone.utc)

try:
    response = client.query_workspace(
        workspace_id=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)

未確認・今後の課題

  • 大量のデータ担った場合、そもそも取得できるか?
    • 処理速度はどれくらいか?
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0