如何确保关联异常的ASP.NET MVC请求数据不被Application Insights自适应采样过滤
解决关联异常的请求被Application Insights自适应采样过滤的问题
当前配置仅排除了Exception类型的采样,但默认自适应采样不会自动关联请求与异常的采样决策,导致异常已记录但对应请求被过滤。以下是无需完全关闭请求采样的解决方案:
推荐方案:自定义关联异常的采样处理器
通过自定义采样逻辑,标记并保留发生异常的请求,同时对正常请求保持自适应采样。
1. 创建自定义采样处理器类
using Microsoft.ApplicationInsights.Channel; using Microsoft.ApplicationInsights.Extensibility; using Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel; using System.Web; namespace YourAppNamespace { public class ExceptionLinkedRequestSamplingProcessor : AdaptiveSamplingTelemetryProcessor { public ExceptionLinkedRequestSamplingProcessor(ITelemetryProcessor next) : base(next) { } protected override bool ShouldSample(ITelemetry item) { // 仅针对请求类型遥测处理 if (item is Microsoft.ApplicationInsights.DataContracts.RequestTelemetry requestTelemetry) { var context = HttpContext.Current; // 检查当前请求上下文是否标记了异常 if (context != null && context.Items.Contains("HasException")) { // 关联异常的请求不采样,直接保留 return false; } } // 其他遥测类型沿用默认自适应采样逻辑 return base.ShouldSample(item); } } }
2. 在异常处理中标记请求上下文
在Global.asax.cs的Application_Error方法中添加标记,记录当前请求是否发生异常:
protected void Application_Error(object sender, EventArgs e) { var exception = Server.GetLastError(); if (exception != null) { // 标记当前请求存在异常 HttpContext.Current.Items["HasException"] = true; } }
3. 修改ApplicationInsights配置
替换原有的自适应采样处理器为自定义处理器,确保配置中的命名空间和程序集名称与实际代码一致:
<TelemetryProcessors> <Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse.QuickPulseTelemetryProcessor, Microsoft.AI.PerfCounterCollector" /> <Add Type="Microsoft.ApplicationInsights.Extensibility.AutocollectedMetricsExtractor, Microsoft.ApplicationInsights" /> <!-- 替换为自定义采样处理器 --> <Add Type="YourAppNamespace.ExceptionLinkedRequestSamplingProcessor, YourAppAssembly"> <MaxTelemetryItemsPerSecond>5</MaxTelemetryItemsPerSecond> <ExcludedTypes>Event;Exception</ExcludedTypes> </Add> <!-- 移除重复的Event采样处理器,避免冲突 --> </TelemetryProcessors>
简化方案:调整采样关联配置(可靠性较低)
若不想编写自定义代码,可尝试开启采样的关联头配置,依赖AI内部的Operation ID关联逻辑保留请求,但无法保证100%生效:
<Add Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.AdaptiveSamplingTelemetryProcessor, Microsoft.AI.ServerTelemetryChannel"> <MaxTelemetryItemsPerSecond>5</MaxTelemetryItemsPerSecond> <ExcludedTypes>Event;Exception</ExcludedTypes> <SamplingPercentageEstimatorSettings> <IncludeCorrelationHeaders>true</IncludeCorrelationHeaders> </SamplingPercentageEstimatorSettings> </Add>
注意事项
- 确保
RequestTrackingTelemetryModule和ExceptionTrackingTelemetryModule配置正常,保证请求与异常的OperationId一致,这是关联的基础。 - 移除配置中重复的自适应采样处理器(当前配置中存在两个针对Event的采样处理器),避免逻辑冲突。
内容的提问来源于stack exchange,提问作者Gary
相关产品推荐
相关产品推荐

