You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在无AD凭据下用C# .NET Core从Application Insights检索日志

无需AD凭据从Application Insights检索日志的方案

以下是几种不需要AD凭据(ClientId、SecretKey)就能检索Application Insights日志的可行方法:

1. 利用Instrumentation Key调用旧版查询API(限经典资源)

这种方式仅适用于经典Application Insights资源(基于工作区的新版资源不支持此方式),你可以直接用已有的Instrumentation Key发起查询请求:

  • 构造请求URL:https://api.applicationinsights.io/v1/apps/{你的Application Insights App ID}/query
  • 请求头添加x-api-key,值为你的Instrumentation Key
  • 请求体传入Kusto查询语句,示例:
    {
      "query": "traces | take 10"
    }
    
  • App ID可从Azure门户获取:进入目标Application Insights资源 → 概述页面右上角的「API访问」→ 复制App ID

2. 启用Azure Function系统托管身份

若你的Function与Application Insights在同一Azure租户下,可通过系统托管身份实现无凭据认证:

  • 进入Azure Function应用的「身份」设置,启用「系统分配」托管身份
  • 进入目标Application Insights资源的「访问控制(IAM)」,添加角色分配:将「Application Insights 读取者」角色分配给该Function应用的系统托管身份
  • 代码中使用Azure SDK(如Azure.Monitor.Query包),通过托管身份自动认证查询日志,C#示例:
    using Azure.Monitor.Query;
    using Azure.Core;
    using System.Threading.Tasks;
    
    public static async Task Run()
    {
        var credential = new DefaultAzureCredential();
        var client = new LogsQueryClient(credential);
        var workspaceId = "{你的工作区ID}"; // 基于工作区的AI资源需填写此ID
        var query = "traces | take 10";
        var result = await client.QueryAsync(workspaceId, query, new QueryTimeRange(TimeSpan.FromHours(24)));
        // 处理查询结果逻辑
    }
    
    此方式无需手动管理AD凭据,身份认证由Azure自动完成。

3. 生成共享访问签名(SAS)令牌

你可以在Azure门户为Application Insights生成临时SAS令牌用于查询:

  • 进入目标Application Insights资源 → 概述页面右上角的「API访问」→「生成SAS令牌」
  • 设置令牌的权限(至少勾选「读取」)和有效期
  • 请求查询API时,将SAS令牌作为Authorization头的值,格式为SharedAccessSignature {SAS令牌内容}

4. 配置日志导出至存储服务(非实时场景)

如果不需要实时查询日志,可通过Application Insights的内置导出功能将日志同步到存储服务:

  • 将日志自动导出到Azure Blob存储、Azure Data Lake Storage或Event Hub
  • 你的Azure Function可直接从这些存储服务读取日志,此类服务可通过连接字符串或托管身份访问,无需AD凭据

内容的提问来源于stack exchange,提问作者SuryaKavitha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 05:45:04