Azure Application Insights与HotChocolate GraphQL框架集成及查询拆分方案咨询
Azure Application Insights与HotChocolate GraphQL集成最优方案
HotChocolate从v12版本开始已原生支持与Azure Application Insights的集成,是目前官方推荐的成熟方案,无需自行拼凑实现,完全可以达到和REST API对接一致的监控体验,支持按GraphQL查询维度拆分所有监控数据。
实现步骤
1. 安装依赖包
安装两个必要的NuGet包:
HotChocolate.Diagnostics:HotChocolate官方提供的诊断工具包,内置Application Insights上报能力Microsoft.ApplicationInsights.AspNetCore:Azure Application Insights官方ASP.NET Core集成包
2. 基础配置
在ASP.NET Core的Program.cs中添加集成配置即可开箱即用:
// 注册Application Insights服务 builder.Services.AddApplicationInsightsTelemetry(builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"]); // 注册HotChocolate GraphQL服务并启用Application Insights诊断 builder.Services.AddGraphQLServer() .AddQueryType<Query>() // 启用Application Insights诊断监听 .AddDiagnosticEventListener<ApplicationInsightsDiagnosticListener>();
3. 自定义监控维度(可选)
如果需要调整上报的监控内容,可以通过ApplicationInsightsDiagnosticOptions自定义配置:
builder.Services.AddGraphQLServer() .AddQueryType<Query>() .AddDiagnosticEventListener(serviceProvider => new ApplicationInsightsDiagnosticListener( serviceProvider.GetRequiredService<TelemetryClient>(), new ApplicationInsightsDiagnosticOptions { RecordOperationName = true, // 上报GraphQL操作名,用于维度筛选 RecordOperationType = true, // 上报操作类型:query/mutation/subscription RecordDocument = true, // 上报完整查询语句 RecordExecutionTime = true, // 上报查询执行耗时 RecordException = true, // 上报查询执行异常 RecordVariables = false, // 可选:上报请求变量,敏感数据建议自行脱敏后再开启 RecordValidationErrors = true // 上报查询校验错误 }));
监控数据维度说明
配置完成后,所有GraphQL请求会作为标准的request遥测数据上报到Application Insights,默认自动携带以下自定义维度,可直接用于筛选、聚合、生成仪表盘:
- GraphQL操作名称:对应查询中定义的operation名
- GraphQL操作类型:区分查询、变更、订阅
- GraphQL执行结果:标识请求是否执行成功
- GraphQL错误数量:请求执行过程中返回的报错总数
- GraphQL查询文档:完整的请求查询语句
如果需要追加业务自定义维度(如租户ID、用户ID等),可以继承ApplicationInsightsDiagnosticListener类,重写对应的执行生命周期方法添加自定义遥测属性即可。
内容的提问来源于stack exchange,提问作者Ricky Gummadi
相关产品推荐
相关产品推荐

