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

使用azure-applicationinsights SDK查询时遇AttributeError错误求助

问题解决方法

核心原因

你使用的azure-applicationinsights 0.1.1属于**旧版Azure SDK(v2)范畴,而azure.identity中的DefaultAzureCredential、ClientSecretCredential是新版Azure SDK(v3)**的凭据体系,两者不兼容——旧版客户端要求凭据必须实现signed_session方法,新版凭据没有该方法,因此抛出AttributeError。

至于ServicePrincipalCredentials引发的密钥错误,大概率是服务主体权限配置问题,而非密钥本身错误。


推荐解决方案:升级到新版SDK

旧版azure-applicationinsights已被官方弃用,微软推荐使用azure-monitor-query包查询Application Insights数据,以下是适配代码:

  1. 安装新版依赖包:
pip install azure-monitor-query azure-identity
  1. 新版查询代码示例:
from azure.identity import DefaultAzureCredential
from azure.monitor.query import LogsQueryClient
from azure.monitor.query.models import QueryTimeRange

def query_app_insights():
    query = 'myEvents | take 10'
    # 替换为你的Application Insights资源ID,格式为:/subscriptions/订阅ID/resourceGroups/资源组/providers/microsoft.insights/components/应用名称
    resource_id = "/subscriptions/xxx/resourceGroups/xxx/providers/microsoft.insights/components/my-app"
    
    creds = DefaultAzureCredential()
    client = LogsQueryClient(creds)
    
    # 执行查询,这里指定查询过去24小时的数据,可根据需求调整时间范围
    result = client.query_resource(
        resource_id,
        query,
        timespan=QueryTimeRange(days=1)
    )
    
    # 遍历输出结果
    for table in result.tables:
        for row in table.rows:
            print(row)

若必须保留旧版SDK的解决方法

如果因特殊场景需继续使用azure-applicationinsights 0.1.1,请按以下步骤调整:

  1. 修正旧版凭据配置:
from azure.applicationinsights import ApplicationInsightsDataClient
from azure.applicationinsights.models import QueryBody
from azure.common.credentials import ServicePrincipalCredentials

def query_app_insights():
    query = 'myEvents | take 10'
    application = 'my-app'
    
    creds = ServicePrincipalCredentials(
        tenant="<你的租户ID>",
        client_id="<你的客户端ID>",
        secret="<你的客户端密钥>",
        # 必须指定Application Insights的API权限范围
        resource="https://api.applicationinsights.io"
    )
    
    client = ApplicationInsightsDataClient(creds)
    result = client.query.execute(application, QueryBody(query=query))
    
    # 输出查询结果
    print(result.tables[0].rows)
  1. 验证服务主体权限:
  • 登录Azure门户,找到目标Application Insights资源,进入访问控制(IAM)页面,为服务主体添加Application Insights组件数据读取者角色。
  • 确认客户端密钥未过期,租户ID、客户端ID无拼写错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 20:05:30