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

如何通过编程读取Azure日志?VS Code扩展读取日志失败求助

解决Application Insights日志读取失败的问题

1. 替换正确的Azure SDK包

你当前使用的@azure/applicationinsights-analytics是旧版SDK,Azure现在推荐使用@azure/monitor-query包来查询Application Insights日志,先安装所需依赖:

npm install @azure/monitor-query @azure/identity

2. 配置资源权限

确保VS Code运行时使用的身份(你的Azure账号)拥有目标Application Insights资源的Application Insights Reader角色:

  • 登录Azure门户,找到目标Application Insights资源
  • 进入「访问控制(IAM)」→「添加」→「添加角色分配」
  • 搜索并选择「Application Insights Reader」角色,添加对应的用户账号

3. 修改代码使用正确的SDK与认证方式

用MonitorQueryClient替代旧客户端,通过DefaultAzureCredential自动复用VS Code的Azure登录身份(适配VS Code扩展场景):

const { MonitorQueryClient } = require("@azure/monitor-query");
const { DefaultAzureCredential } = require("@azure/identity");

async function retrieveLogs() {
  // 替换为你的Application Insights资源ID,格式示例:/subscriptions/xxx/resourceGroups/xxx/providers/microsoft.insights/components/xxx
  const resourceId = "你的Application Insights资源ID";
  const query = "requests | take 10";
  // 设置查询的时间范围,这里取最近24小时的数据
  const timeRange = { 
    start: new Date(Date.now() - 24 * 60 * 60 * 1000), 
    end: new Date() 
  };

  // 自动使用VS Code的Azure登录身份完成认证
  const credential = new DefaultAzureCredential();
  const client = new MonitorQueryClient(credential);

  try {
    const result = await client.queryLogs(resourceId, query, timeRange);
    if (result.tables.length > 0) {
      console.log("查询到的日志数据:");
      console.log(result.tables[0].rows);
    } else {
      console.log("未查询到符合条件的日志");
    }
  } catch (error) {
    console.error("读取日志失败:", error.message);
    // 如需排查细节,可打开下方注释打印完整错误信息
    // console.error(error);
  }
}

retrieveLogs();

4. 常见问题排查

  • 认证失败:确认VS Code已通过Azure Account扩展登录Azure,且账号拥有对应资源的访问权限
  • 查询无结果:检查timeRange是否覆盖日志产生的时间,或验证Kusto查询语句的正确性
  • 依赖报错:删除node_modules目录后重新执行npm install安装依赖

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 11:55:26