我想使用 Azure API 管理中的日志并查询成功调用 API 的数量,或者用户过去一个月在 C#/dotnet 中进行的 API 调用次数。
我只需要一种访问数据的方法,但我很难找到实现此目的的方法,因为许多当前现有的解决方案似乎已被弃用。
from azure.identity import DefaultAzureCredential
from azure.monitor.query import LogsQueryClient
from azure.identity import ClientSecretCredential
from azure.core.exceptions import HttpResponseError
import pandas as pd
from datetime import timedelta
from azure.monitor.query import LogsQueryStatus
subscription_id = "..."
client_id = "..."
client_secret = "..."
tenant_id = "..."
credential = ClientSecretCredential(
tenant_id=tenant_id,
client_id=client_id,
client_secret=client_secret
)
client = LogsQueryClient(credential)
query = "ApiManagementGatewayLogs ..."
try:
response = client.query_workspace(os.environ["LOGS_WORKSPACE_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)
上面是我当前的代码,我已转移到 python 而不是 dotnet,并且“LOGS_WORKSPACE_ID”我不知道如何修复,因为我只是尝试访问 Azure 门户的监视器 -> 日志并尝试查询。 上面的代码基于:https://learn.microsoft.com/en-us/python/api/azure-monitor-query/azure.monitor.query.logsqueryclient?view=azure-python
我可以使用下面的代码获取 APIM 日志。
from azure.identity import DefaultAzureCredential
from azure.monitor.query import LogsQueryClient, LogsQueryStatus
from azure.core.exceptions import HttpResponseError
import pandas as pd
from datetime import timedelta
credential = DefaultAzureCredential()
client = LogsQueryClient(credential)
query = "ApiManagementGatewayLogs"
try:
response = client.query_workspace("{LOGS_WORKSPACE_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)
pd.set_option('display.max_columns', None)
print(df)
except HttpResponseError as err:
print("something fatal happened")
print(err)
输出-
os.environ["LOGS_WORKSPACE_ID"]
设置工作区 ID,则执行 set LOGS_WORKSPACE_ID="your_workspace_id"
命令设置 Id。