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

如何使用.NET查询工作区关联的Azure Application Insights日志?

使用Azure.Monitor.Query查询关联LAW的Application Insights日志

完全可以用新的Azure.Monitor.Query NuGet包直接执行Application Insights的原生查询,不需要手动把Requests改成AppRequests这类带前缀的表名。具体实现步骤如下:

1. 安装必要的NuGet包

需要安装两个核心包:

  • Azure.Monitor.Query:负责日志查询的核心功能
  • Azure.Identity:用于Azure服务的身份验证(支持本地开发、生产环境的多种身份验证方式)

可以通过命令行安装:

dotnet add package Azure.Monitor.Query
dotnet add package Azure.Identity

2. 编写查询代码示例

直接指定Application Insights的资源ID作为查询目标,就能用原生的AI查询语句执行,SDK会自动处理底层LAW的表映射:

using Azure.Core;
using Azure.Identity;
using Azure.Monitor.Query;
using Azure.Monitor.Query.Models;

var credential = new DefaultAzureCredential();
var client = new LogsQueryClient(credential);

// 替换为你的Application Insights资源ID
string aiResourceId = "/subscriptions/{subscription-id}/resourceGroups/{resource-group}/providers/microsoft.insights/components/{ai-component-name}";
string query = "Requests | take 10";

Response<LogsQueryResult> response = await client.QueryAsync(
    resourceId: aiResourceId,
    query: query,
    timeRange: new QueryTimeRange(TimeSpan.FromDays(1))
);

foreach (LogsTable table in response.Value.Tables)
{
    foreach (LogsTableRow row in table.Rows)
    {
        // 按需处理查询结果
        Console.WriteLine($"请求ID: {row["id"]}, 耗时: {row["duration"]}");
    }
}

3. 关键说明

  • 当针对Application Insights资源ID发起查询时,SDK会自动关联到底层的Log Analytics工作区,并完成表名映射(比如将Requests对应到AppRequests),无需手动修改查询语句。
  • 确保身份验证凭据(如本地Azure CLI账号、生产环境托管标识)拥有Application Insights资源的Monitoring Reader或更高权限。
  • 只有直接查询LAW资源ID时才需要使用带App前缀的表名;针对AI资源ID查询时,使用原生AI表名即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 21:45:02