AzureのPython SDKでActivity Logを取得する方法を調べました。
使うモジュールについて
そもそもどのモジュールで取得するのかわからなかったのですが、以下のIssueにヒントがありました。
こちらに記載されている ActivityLogsOperations
を使うようです。
ActivityLogsOperations
のコードはこちら になります。
ただ、コードを読むとわかるのですが、ActivityLogsOperations
は直接使うものではなく、こちらの MonitorManagementClientを通して使います。
サンプルコード
Activity Logsを取得・出力するサンプルコードです。
azure-mgmt-monitor
と azure-identity
をpipでインストールしておきます。
import os from datetime import datetime, timedelta from azure.identity import DefaultAzureCredential from azure.mgmt.monitor import MonitorManagementClient os.environ["AZURE_TENANT_ID"] = "xxxxxxx" os.environ["AZURE_CLIENT_ID"] = "xxxxxxx" os.environ["AZURE_CLIENT_SECRET"] = "xxxxxxx" subscription_id = "xxxxxxx" credential = DefaultAzureCredential() client = MonitorManagementClient(credential=credential, subscription_id=subscription_id) # 直近6時間分の特定ResourceGroupのログを取得 to_dt = datetime.utcnow() from_dt = to_dt - timedelta(hours=6) resource_group = "my-rg" log_filter = f"eventTimestamp ge '{from_dt.isoformat()}Z' and eventTimestamp le '{to_dt.isoformat()}Z' and resourceGroupName eq '{resource_group}'" # 取得する項目を選択 fields = "operationName,status,eventTimestamp,resourceGroupName,level" log_entries = client.activity_logs.list(filter=log_filter, select=fields) for entry in log_entries: e = entry.as_dict() print(f"{e['level']}|{e['operation_name']['localized_value']}|{e['status']['localized_value']}|{e['event_timestamp']}|{e['resource_group_name']}") print("-" * 30)
出力は以下のようになります。
Informational|Create or Update Virtual Machine|Succeeded|2022-03-03T11:09:08.467917Z|my-rg ------------------------------ Informational|Create or Update Network Security Group|Succeeded|2022-03-03T11:09:06.219394Z|my-rg ------------------------------ Informational|Create or Update Virtual Network|Succeeded|2022-03-03T11:09:05.918008Z|my-rg ------------------------------ Informational|Create or Update Public Ip Address|Succeeded|2022-03-03T11:09:03.423489Z|my-rg 省略......
filter
や select
に指定する項目は以下のコメントを読むとわかります。