如何在Application Insights中禁用HTTP请求追踪?
解决Application Insights升级后HTTP请求事件持续输出的问题
问题分析
你升级到Microsoft.ApplicationInsights.AspNetCore 2.21.0后,Azure事件日志中出现的是REQUEST类型的请求遥测,而当前配置的EnableDependencyTrackingTelemetryModule=false仅控制依赖项跟踪(比如调用外部服务的遥测),对请求遥测无效;EnableAdaptiveSampling=false只是关闭采样逻辑,不会停止请求遥测的收集和发送。
解决方案
方案1:完全关闭请求遥测收集
在配置文件的ApplicationInsights节点下添加以下配置,直接禁用请求跟踪模块:
"ApplicationInsights": { "EnableAdaptiveSampling": false, "EnableDependencyTrackingTelemetryModule": false, "InstrumentationKey": "0298fcb7-58c1-4a7f-9030-fe99f3a60504", "RequestTrackingTelemetryModule": { "Enabled": false } }
方案2:通过代码禁用请求跟踪模块
如果配置文件方式不生效,可以在启动代码中手动移除请求跟踪模块:
- 对于.NET 6+(Program.cs):
var builder = WebApplication.CreateBuilder(args); builder.Services.AddApplicationInsightsTelemetry(); // 移除请求跟踪模块 builder.Services.RemoveAll<IRequestTrackingTelemetryModule>();
- 对于.NET Core 3.1及更早版本(Startup.cs):
public void ConfigureServices(IServiceCollection services) { services.AddApplicationInsightsTelemetry(); services.RemoveAll<IRequestTrackingTelemetryModule>(); }
方案3:过滤特定请求(保留其他请求遥测)
如果不想完全关闭所有请求遥测,仅过滤掉轮询的Orders/GetOrders或目标请求,可以自定义遥测处理器:
- 创建自定义处理器类:
using Microsoft.ApplicationInsights.Channel; using Microsoft.ApplicationInsights.Extensibility; public class FilterPollingRequestsProcessor : ITelemetryProcessor { private ITelemetryProcessor Next { get; set; } public FilterPollingRequestsProcessor(ITelemetryProcessor next) { Next = next; } public void Process(ITelemetry item) { if (item is RequestTelemetry request) { // 过滤掉目标请求路径 if (request.Name.Contains("Orders/GetOrders") || request.Url.AbsolutePath.Contains("/viewModel/quotes")) { return; // 不发送该遥测 } } Next.Process(item); } }
- 在启动代码中注册处理器:
- .NET 6+(Program.cs):
builder.Services.AddApplicationInsightsTelemetry(); builder.Services.AddSingleton<ITelemetryProcessor, FilterPollingRequestsProcessor>();
- .NET Core 3.1及更早版本(Startup.cs):
public void ConfigureServices(IServiceCollection services) { services.AddApplicationInsightsTelemetry(); services.AddSingleton<ITelemetryProcessor, FilterPollingRequestsProcessor>(); }
内容的提问来源于stack exchange,提问作者user365462
相关产品推荐
相关产品推荐

