如何用C#/.NET获取Azure API Management日志?Python代码Workspace ID配置疑问
问题描述
我需要在C#/.NET环境中查询Azure API Management的日志数据,比如统计成功调用的API数量、特定用户近一个月的API调用次数等,但目前多数现有方案已被弃用,找不到可行的实现方式。
于是我转而用Python编写了一段代码,目标是访问Azure门户的Monitor->Logs并执行查询(代码基于微软官方文档实现),但不清楚如何配置LOGS_WORKSPACE_ID。代码如下:
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 import os # 原代码遗漏os模块,需补充才能读取环境变量 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)
解决方案
一、配置LOGS_WORKSPACE_ID的方法
LOGS_WORKSPACE_ID是存储APIM日志的Log Analytics工作区ID,获取步骤如下:
- 登录Azure门户,找到对应的Log Analytics工作区(需确认APIM已配置将日志导出到该工作区)
- 进入工作区的概述页面,在右侧面板中直接复制
工作区ID的值 - 代码中可以直接将
os.environ["LOGS_WORKSPACE_ID"]替换为复制的ID字符串(如"12345678-1234-1234-1234-1234567890ab"),或者将该ID设置为系统环境变量
注意事项
- 确保APIM实例已配置日志导出到目标Log Analytics工作区,否则查询会返回空结果
- 用于认证的服务主体(Client ID/Secret/Tenant ID)需要拥有该工作区的Log Analytics Reader权限,否则会触发权限不足的错误
二、C#/.NET环境的可行实现方案
如果仍需在C#/.NET中实现,推荐使用官方未弃用的Azure.Monitor.Query NuGet包,核心逻辑如下:
- 安装NuGet包:
Install-Package Azure.Monitor.Query - 使用
LogsQueryClient结合ClientSecretCredential完成认证,调用QueryWorkspaceAsync执行日志查询
示例代码
using Azure.Identity; using Azure.Monitor.Query; using Azure.Monitor.Query.Models; using System; using System.Threading.Tasks; namespace ApimLogQuery { class Program { static async Task Main(string[] args) { // 替换为你的实际参数 string tenantId = "你的租户ID"; string clientId = "你的客户端ID"; string clientSecret = "你的客户端密钥"; string workspaceId = "你的Log Analytics工作区ID"; var credential = new ClientSecretCredential(tenantId, clientId, clientSecret); var logClient = new LogsQueryClient(credential); // 示例查询:统计近30天成功调用的各API次数 string query = @"ApiManagementGatewayLogs | where TimeGenerated >= ago(30d) | where ResultType == 'Success' | summarize CallCount = count() by ApiName"; try { var response = await logClient.QueryWorkspaceAsync(workspaceId, query, TimeSpan.FromDays(30)); if (response.Status == LogsQueryStatus.Success) { foreach (var table in response.Tables) { Console.WriteLine("=== 成功调用API统计 ==="); foreach (var row in table.Rows) { Console.WriteLine($"API名称: {row["ApiName"]} | 调用次数: {row["CallCount"]}"); } } } } catch (Exception ex) { Console.WriteLine($"查询失败:{ex.Message}"); } } } }
内容的提问来源于stack exchange,提问作者Jeff
相关产品推荐
相关产品推荐

