Azure VM上AddApplicationInsightsTelemetryWorkerService控制台应用AI追踪缺失
问题描述
我使用Visual Studio 2022构建了一个控制台应用:
- 最初通过
ILogger埋点追踪,在Azure VM上运行时,Application Insights(以下简称AI)事务日志能显示追踪条目,但每个条目独立无Trace Id; - 之后在
ConfigureServices函数中添加AddApplicationInsightsTelemetryWorkerService,并用TelemetryClient.StartOperation方法包裹代码与追踪逻辑; - 本地运行时,AI可正常显示所有带Trace Id的追踪,但部署到Azure VM运行相同代码时,追踪完全无法被收集和显示;
- 本地与Azure环境共用同一
appsettings.json配置文件。
相关代码
IHost host = CreateHostBuilder(args); string version = "#{Build.BuildNumber}#"; Activity activity = new Activity($"Launch v {version} at {DateTime.Now}"); // Loop thru apps. If the time < now, run the command ILogger<ScraperCommandModel>? logger = host.Services.GetService<ILogger<ScraperCommandModel>>(); IConfiguration? configuration = host.Services.GetService<IConfiguration>(); TelemetryClient telemetryClient = host.Services.GetRequiredService<TelemetryClient>(); //string AIConn = configuration?["APPLICATIONINSIGHTS_CONNECTION_STRING"] ?? string.Empty; DateTime now = DateTime.Now; if (logger == null) { Console.Error.WriteLine($"Could not create logger"); return; } using (telemetryClient.StartOperation<RequestTelemetry>(activity)) { logger.LogInformation("Version {ver} Starting. ({time})", version, DateTime.Now); logger.LogInformation("Completed."); } // implementatinon of 'CreateHostBuilder' static method and create host object IHost CreateHostBuilder(string[] strings) { IHostBuilder builder = Host.CreateDefaultBuilder(); builder .ConfigureLogging((context, logging) => { string AIKey = context.Configuration["APPLICATIONINSIGHTS_INSTRUMENTATIONKEY"] ?? string.Empty; string AIConn = context.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"] ?? string.Empty; logging.ClearProviders(); logging.AddConsole(); }) .ConfigureServices((context, services) => { string AIConn = context.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"] ?? string.Empty; services.AddLogging(); services.AddApplicationInsightsTelemetryWorkerService((options) => options.ConnectionString = AIConn); }); return builder.Build(); }
配置文件(appsettings.json)
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Information" }, "ApplicationInsights": { "LogLevel": { "Default": "Information" }, "INSTRUMENTATIONKEY": "XXX", "ConnectionString": "InstrumentationKey=XXX;IngestionEndpoint=https://eastus2-3.in.applicationinsights.azure.com/;LiveEndpoint=https://eastus2.livediagnostics.monitor.azure.com/" } } }
排查与解决步骤
1. 验证Azure VM网络连通性
确保Azure VM能访问AI的IngestionEndpoint(https://eastus2-3.in.applicationinsights.azure.com/),可在VM上执行以下命令测试:
Invoke-WebRequest -Uri https://eastus2-3.in.applicationinsights.azure.com/
若请求失败,需检查VM的防火墙规则、网络安全组(NSG)是否拦截了出站流量。
2. 确认配置加载正确性
在代码中添加日志输出,验证APPLICATIONINSIGHTS_CONNECTION_STRING是否被正确读取:
// 在CreateHostBuilder的ConfigureServices中添加 Console.WriteLine($"Loaded AI Connection String: {AIConn}");
同时检查Azure VM是否设置了同名环境变量,环境变量会覆盖配置文件中的值,导致读取错误。
3. 修正Activity使用逻辑
手动创建的Activity未启动,无法生成有效的Trace Id,可调整为两种方式:
- 直接使用
StartOperation的字符串重载,由AI自动管理Activity:using (var operation = telemetryClient.StartOperation<RequestTelemetry>($"Launch v {version} at {DateTime.Now}")) { logger.LogInformation("Version {ver} Starting. ({time})", version, DateTime.Now); logger.LogInformation("Completed."); } - 手动启动并停止Activity:
activity.Start(); using (telemetryClient.StartOperation<RequestTelemetry>(activity)) { logger.LogInformation("Version {ver} Starting. ({time})", version, DateTime.Now); logger.LogInformation("Completed."); } activity.Stop();
4. 添加Application Insights日志提供者
当前ConfigureLogging仅添加了Console日志提供者,需补充AI日志提供者,否则ILogger的日志无法发送到AI:
.ConfigureLogging((context, logging) => { logging.ClearProviders(); logging.AddConsole(); // 添加AI日志提供者 logging.AddApplicationInsights(context.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"]); })
5. 关闭采样避免日志丢失
AI默认采样可能导致部分日志被丢弃,可在配置中强制关闭采样:
"ApplicationInsights": { "Sampling": { "Enabled": false, "Percentage": 100 }, // 原有配置... }
6. 检查运行环境一致性
确认本地与Azure VM的.NET版本一致,且VM已安装对应版本的.NET运行时;同时确保应用进程有足够权限发送HTTP请求到AI端点。
内容的提问来源于stack exchange,提问作者Darryl Challenger
相关产品推荐
相关产品推荐

