切换Application Insights至连接字符串后异常无法在Azure中显示
Application Insights切换连接字符串后异常无法显示的解决方案
微软已宣布Application Insights的Instrumentation Key将被弃用,推荐使用连接字符串。但切换后,通过ILogger记录的日志可正常显示在Azure Application Insights中,抛出的异常却无法被捕获显示。
切换前可正常工作的代码
private static IServiceCollection ConfigureServices() { //here I just read app settings.json file IConfiguration config = LoadConfiguration(); IServiceCollection services = new ServiceCollection(); services.AddLogging(builder => { builder.AddConfiguration(config); builder.AddConsole(); builder.AddApplicationInsights(config.GetSection("InstrumentationKey").Value) .AddFilter("", LogLevel.Trace); }) .AddSingleton<IExampleService, ExampleService>(); return services; }
切换至连接字符串后的代码
private static IServiceCollection ConfigureServices() { IConfiguration config = LoadConfiguration(); IServiceCollection services = new ServiceCollection(); services.AddLogging(builder => { builder.AddConfiguration(config); builder.AddConsole(); builder.AddApplicationInsights( telConfig => telConfig.ConnectionString = config.GetSection("AIConnectionString").Value), ailoptions => {}).AddFilter("", LogLevel.Trace); }) .AddSingleton<IExampleService, ExampleService>(); return services; }
问题分析
使用连接字符串配置时,默认的异常追踪逻辑可能未被正确初始化,或者ILogger的异常收集选项未显式启用,导致抛出的异常无法被Application Insights捕获。
解决方案
1. 显式配置异常追踪选项
修改AddApplicationInsights的配置,开启TrackExceptionsAsExceptionTelemetry选项,确保ILogger记录的异常被转换为Exception Telemetry:
private static IServiceCollection ConfigureServices() { IConfiguration config = LoadConfiguration(); IServiceCollection services = new ServiceCollection(); services.AddLogging(builder => { builder.AddConfiguration(config); builder.AddConsole(); builder.AddApplicationInsights( telConfig => { telConfig.ConnectionString = config.GetSection("AIConnectionString").Value; }, ailoptions => { // 显式开启异常追踪 ailoptions.TrackExceptionsAsExceptionTelemetry = true; }).AddFilter("", LogLevel.Trace); }) .AddSingleton<IExampleService, ExampleService>(); return services; }
2. 针对后台服务场景添加Telemetry Worker Service
如果是Worker Service或后台服务,需添加AddApplicationInsightsTelemetryWorkerService来确保未处理的异常被收集:
services.AddLogging(builder => { // 原有配置... }) .AddApplicationInsightsTelemetryWorkerService(config => { config.ConnectionString = config.GetSection("AIConnectionString").Value; }) .AddSingleton<IExampleService, ExampleService>();
3. 确保异常通过ILogger正确记录
直接抛出的未处理异常需要依赖Telemetry服务收集,而通过ILogger.LogError记录的异常更易被捕获,建议在catch块中显式记录:
public void DoWork() { try { throw new InvalidOperationException("测试异常"); } catch (Exception ex) { _logger.LogError(ex, "执行操作时发生异常"); throw; // 可选:保留异常抛出,让上层或Telemetry服务处理 } }
4. 验证日志级别配置
确保appsettings.json中Application Insights的日志级别包含Error及以上:
"Logging": { "LogLevel": { "Default": "Trace" }, "ApplicationInsights": { "LogLevel": { "Default": "Trace" } } }
5. 临时禁用采样验证
自适应采样可能过滤异常,可临时禁用采样排查:
telConfig.EnableAdaptiveSampling = false;
内容的提问来源于stack exchange,提问作者Aamon
相关产品推荐
相关产品推荐

