如何配置Serilog停止记录Home/Index请求?
停止记录GET Home/Index请求到Application Insights的解决方案
针对你的Service Fabric ASP.NET Core应用,以下几种方案可以停止记录频繁的GET Home/Index请求:
方案一:自定义遥测处理器过滤请求(推荐,针对AI自动收集的请求遥测)
Application Insights默认会收集所有HTTP请求遥测,你可以通过自定义ITelemetryProcessor过滤掉指定请求:
- 创建过滤处理器类
using Microsoft.ApplicationInsights.Channel; using Microsoft.ApplicationInsights.DataContracts; using Microsoft.ApplicationInsights.Extensibility; public class FilterHomeIndexRequestsProcessor : ITelemetryProcessor { private readonly ITelemetryProcessor _nextProcessor; public FilterHomeIndexRequestsProcessor(ITelemetryProcessor nextProcessor) { _nextProcessor = nextProcessor; } public void Process(ITelemetry item) { if (item is RequestTelemetry requestTelemetry) { // 匹配GET方法的Home/Index请求 if (requestTelemetry.HttpMethod.Equals("GET", System.StringComparison.OrdinalIgnoreCase) && requestTelemetry.Url.AbsolutePath.Equals("/Home/Index", System.StringComparison.OrdinalIgnoreCase)) { // 跳过记录该请求 return; } } // 处理其他遥测数据 _nextProcessor.Process(item); } }
- 在
Web.cs的ConfigureServices中注册处理器
找到ConfigureServices代码块,添加以下注册逻辑:
// 确保已引用Microsoft.ApplicationInsights.AspNetCore包 services.AddApplicationInsightsTelemetry(); // 注册自定义过滤处理器 services.AddSingleton<ITelemetryProcessor>(serviceProvider => new FilterHomeIndexRequestsProcessor(serviceProvider.GetRequiredService<ITelemetryProcessor>()));
方案二:通过Serilog过滤日志条目(针对Serilog记录的请求日志)
如果这些请求是通过Serilog输出的日志,可在Serilog配置中添加过滤规则:
修改Web.cs中的Serilog配置段,增加Filter.ByExcluding规则:
.UseSerilog((host, logger) => { var appInsightsOptions = configuration.GetRequiredSection("AppInsights").Get<AppInsightsOptions>(); var telemetryConfiguration = new TelemetryConfiguration(appInsightsOptions.InstrumentationKey); logger .MinimumLevel.Warning() .Enrich.FromLogContext() .Enrich.WithProperty("ApplicationName", host.HostingEnvironment.ApplicationName) .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning) // 过滤GET Home/Index的日志条目 .Filter.ByExcluding(logEvent => logEvent.Properties.TryGetValue("RequestPath", out var pathVal) && pathVal.ToString().Equals("\"/Home/Index\"", System.StringComparison.OrdinalIgnoreCase) && logEvent.Properties.TryGetValue("RequestMethod", out var methodVal) && methodVal.ToString().Equals("\"GET\"", System.StringComparison.OrdinalIgnoreCase)) .WriteTo.ApplicationInsights(telemetryConfiguration, TelemetryConverter.Events); })
方案三:门户端设置采样规则(无需代码修改)
如果你不想改动代码,可直接在Application Insights门户配置采样规则:
- 进入你的Application Insights资源,找到数据采样选项
- 添加自定义采样规则,选择请求遥测类型
- 设置过滤条件为
Url contains /Home/Index and Request method is GET,将采样比例设为0%
验证方式
配置完成后,等待30分钟左右查看Application Insights的请求日志,确认GET Home/Index请求已不再被记录。
内容的提问来源于stack exchange,提问作者Raju Donthula
相关产品推荐
相关产品推荐

