如何在C#类中从Application Insights获取Azure Media Player事件数据
从C#查询Application Insights中的自定义事件数据
核心结论
TelemetryClient仅用于发送遥测数据到Application Insights,无法查询已存储的日志。你提到的LogsQueryClient是Azure Monitor SDK提供的正确工具,专门用于查询Application Insights(以及Log Analytics工作区)的日志数据。
实现步骤
1. 安装必要的NuGet包
需要两个核心包:
Azure.Monitor.Query:提供日志查询能力Azure.Identity:提供Azure服务的身份认证(支持本地开发、Azure托管环境等场景)
在Package Manager Console执行:
Install-Package Azure.Monitor.Query Install-Package Azure.Identity
2. 编写查询代码示例
以下是完整的C#代码,用于查询"AssetPlayBackData"事件并提取你需要的播放数据:
using Azure.Identity; using Azure.Monitor.Query; using Azure.Monitor.Query.Models; using System; using System.Threading.Tasks; public class ApplicationInsightsQueryService { // 替换为你的Application Insights的Workspace ID private const string WorkspaceId = "your-application-insights-workspace-id"; // 替换为你的Application Insights资源ID(可选,用于指定特定资源查询) private const string AppInsightsResourceId = "/subscriptions/{subscription-id}/resourceGroups/{resource-group}/providers/microsoft.insights/components/{app-insights-name}"; public async Task QueryAssetPlaybackData() { // 初始化LogsQueryClient,使用默认身份认证(本地开发用Azure CLI/VS登录,生产用托管标识) var client = new LogsQueryClient(new DefaultAzureCredential()); // 编写Kusto查询语句:筛选自定义事件,提取所需属性 var query = @" customEvents | where name == 'AssetPlayBackData' | project Timestamp = timestamp, AssetName = customDimensions['assetName'], PlayStartTime = customDimensions['playStartTime'], PlayEndTime = customDimensions['playEndTime'], VisitCount = toint(customDimensions['visitCount']), PlaybackDuration = todouble(customDimensions['playbackDuration']), Location = customDimensions['location'] | order by Timestamp desc "; // 设置查询时间范围(示例:最近7天) var timeRange = new QueryTimeRange(TimeSpan.FromDays(7)); // 执行查询:可以指定Workspace ID或直接用Application Insights资源ID var response = await client.QueryWorkspaceAsync(WorkspaceId, query, timeRange); // 遍历查询结果 foreach (var row in response.Value.Table.Rows) { Console.WriteLine($"资产名称: {row["AssetName"]}"); Console.WriteLine($"观看时长: {row["PlaybackDuration"]} 秒"); Console.WriteLine($"访问次数: {row["VisitCount"]}"); Console.WriteLine($"位置: {row["Location"]}"); Console.WriteLine("---"); } } }
3. 关键说明
- Kusto查询语法:Application Insights的日志存储在Log Analytics工作区中,使用Kusto查询语言。
customEvents表存储所有自定义事件,customDimensions字段包含你前端传入的trackingData属性。 - 身份认证:
DefaultAzureCredential会自动适配不同环境:- 本地开发:使用Azure CLI、Visual Studio或Azure PowerShell的登录凭据
- Azure托管环境:使用应用服务/虚拟机的托管标识
- 权限配置:确保执行查询的身份拥有Application Insights Reader或Log Analytics Reader角色权限。
4. 替代方案(可选)
如果需要批量处理或持久化数据,可以将Application Insights的日志导出到Azure Blob存储/ADLS Gen2,然后通过C#读取存储中的文件进行处理。这种方式适合大数据量的离线分析场景。
内容的提问来源于stack exchange,提问作者Mario Lada Martínez
相关产品推荐
相关产品推荐

