ASP.NET Core 3.1后台作业无InstrumentationKey遥测告警如何解决
问题解决方案
该报错的根本原因是Application Insights内部的内置采集模块(性能计数器、心跳检测等)使用的Telemetry配置实例未正确获取到InstrumentationKey,15分钟为内置性能指标的默认上报周期,因此会固定触发警告。按以下步骤修复即可:
- 统一相关NuGet包版本
你当前使用的Microsoft.ApplicationInsights.NLogTarget和Microsoft.ApplicationInsights.WorkerService版本不一致,会导致两个包引用的Telemetry配置上下文不共享,配置无法互通,需将两个包版本对齐,保持两者版本号一致即可,示例如下:
<PackageReference Include="Microsoft.ApplicationInsights.NLogTarget" Version="2.15.0" /> <PackageReference Include="Microsoft.ApplicationInsights.WorkerService" Version="2.15.0" />
也可统一升级到更高的正式版本。
2. 调整服务注册和配置逻辑
不要仅单独为NLog Target设置InstrumentationKey,直接复用DI容器中注入的完整TelemetryConfiguration实例,同时给全局静态配置实例赋值,覆盖所有内置模块的配置:
services.AddApplicationInsightsTelemetryWorkerService(options => Configuration.GetSection("ApplicationInsights").Bind(options) ); // 构建服务提供器后配置NLog与全局配置 var serviceProvider = services.BuildServiceProvider(); var telemetryConfig = serviceProvider.GetRequiredService<TelemetryConfiguration>(); // 给全局静态实例赋值,解决内置模块直接调用静态实例的问题 TelemetryConfiguration.Active.InstrumentationKey = telemetryConfig.InstrumentationKey; // 配置NLog Target var aiTarget = NLog.LogManager.Configuration.FindTargetByName<ApplicationInsightsTarget>("ai"); if (aiTarget != null) { // 直接传入完整配置实例,比单独设置Key更稳妥 aiTarget.TelemetryConfiguration = telemetryConfig; NLog.LogManager.ReconfigExistingLoggers(); }
- 修改appsettings配置项
WorkerService场景下不需要开启EnableActiveTelemetryConfigurationSetup,该配置是为ASP.NET Core Web应用设计的,关闭即可避免配置冲突:
"ApplicationInsights": { "InstrumentationKey": "instrumentation-key", "DeveloperMode": false, "EnableRequestTrackingTelemetryModule": true, "EnableAdaptiveSampling": false, "EnableActiveTelemetryConfigurationSetup": false }
完成以上修改后重启服务,即可消除该周期性警告。
内容的提问来源于stack exchange,提问作者Amir
相关产品推荐
相关产品推荐

