😊

【Azure/Python】Log Analyticsにデータをエクスポートする

に公開

執筆日

2025/3/17

やること

Azureの診断設定でLog AnalyticsにExportした結果をLocalにcsvで保存する

前提

  • 以下の手順でサービスプリンシパルの作成/シークレット値の取得が完了していること

https://zenn.dev/headwaters/articles/e82aca7bec3579

手順

  1. 以下のライブラリーをinstallする
pip install azure-identity azure-monitor-query pandas
  1. 以下を実行する
from azure.identity import ClientSecretCredential
from azure.monitor.query import LogsQueryClient, LogsQueryStatus
import pandas as pd
import datetime
from datetime import timedelta
# Azureの認証情報(環境変数や直接指定でも可能)
credential = ClientSecretCredential(
    tenant_id=<"テナントID">,
    client_id=<"サービスプリンシパルのID">,
    client_secret=<"サービスプリンシパルの値">
)

workspace_id = <"Log Analytics WorkspaceのID">
client = LogsQueryClient(credential)

# クエリ (Kustoクエリ言語で指定,今回はAppServiceのConsoleログを出力)
query = """
AppServiceConsoleLogs
"""

# クエリの実行
timespan = timedelta(days=1)  
response = client.query_workspace(workspace_id, query, timespan=timespan)

if response.status == LogsQueryStatus.SUCCESS and response.tables and response.tables[0].rows:
    df = pd.DataFrame(data=response.tables[0].rows, columns=response.tables[0].columns)
    df.to_csv("loganalytics_export.csv", index=False, encoding='utf-8-sig')
    print("データのエクスポートが完了しました。")
else:
    print("クエリ実行中にエラーが発生しました。", response.partial_error)
  1. loganalytics_export.csvが出力されたことを確認する

参考資料

https://learn.microsoft.com/ja-jp/python/api/overview/azure/monitor-query-readme?view=azure-python

ヘッドウォータース

Discussion