如何通过代码获取Azure Application Insights中的事务日志
通过代码获取Azure Application Insights事务日志的实现方法
前置准备
操作前需先在Azure门户对应Application Insights资源的「API 访问」页面获取两个凭证:
- Application ID(应用ID):资源的唯一标识
- API 访问密钥:接口调用的鉴权凭证,请勿对外泄露
实现方式
1. C# 实现
首先安装NuGet包:Microsoft.Azure.ApplicationInsights.Query
示例代码:
using Microsoft.Azure.ApplicationInsights.Query; using Microsoft.Azure.ApplicationInsights.Query.Models; var appId = "替换为你的Application ID"; var apiKey = "替换为你的API密钥"; var client = new ApplicationInsightsDataClient(new ApiKeyServiceClientCredentials(apiKey)); // 查询最近24小时的所有事务请求日志,可根据需求调整KQL语句 var queryResults = await client.Query.ExecuteAsync(appId, "requests | where timestamp > ago(24h) | project timestamp, operation_Name, success, duration, customDimensions"); // 遍历获取事件详情 foreach(var row in queryResults.Tables[0].Rows) { var eventTime = row[0]; var operationName = row[1]; // 按需取对应字段即可 }
2. Python 实现
首先安装依赖包:pip install applicationinsights-query
示例代码:
from applicationinsights_query import ApplicationInsightsDataClient from msrest.authentication import ApiKeyCredentials app_id = "替换为你的Application ID" api_key = "替换为你的API密钥" credentials = ApiKeyCredentials(in_headers={"X-Api-Key": api_key}) client = ApplicationInsightsDataClient(credentials) # 执行查询 query = "requests | where timestamp > ago(24h) | project timestamp, operation_Name, success, duration" response = client.query.execute(app_id, query) # 解析结果 for row in response.tables[0].rows: event_time, op_name, is_success, duration = row # 处理逻辑
3. 通用Rest API调用(适配所有语言)
直接调用官方接口即可,无需安装SDK:
- 接口地址:
https://api.applicationinsights.io/v1/apps/{替换为你的Application ID}/query - 请求方式:POST
- 请求头:添加
X-Api-Key: {替换为你的API密钥}、Content-Type: application/json - 请求体示例:
{ "query": "requests | where timestamp > ago(24h)", "timespan": "P1D" }
curl调用示例:
curl -X POST \ https://api.applicationinsights.io/v1/apps/你的应用ID/query \ -H 'Content-Type: application/json' \ -H 'X-Api-Key: 你的API密钥' \ -d '{"query":"requests | where timestamp > ago(24h) | limit 100"}'
常用查询参考
你可以根据核验需求调整KQL(Kusto查询语言)语句,常见场景如下:
- 查询最近24小时所有失败的事务:
requests | where success == false and timestamp > ago(24h) - 查询响应时长超过1秒的慢事务:
requests | where duration > 1000 and timestamp > ago(1h) - 按事务名称统计最近7天的调用量:
requests | where timestamp > ago(7d) | summarize count() by operation_Name
如果需要查询其他类型的事务事件,可替换查询的表名,比如依赖调用对应dependencies表、异常对应exceptions表、自定义事件对应customEvents表即可
内容的提问来源于stack exchange,提问作者Arun Kumar
相关产品推荐
相关产品推荐

