By default Application Insights will log every 404 error in your web app as an error. I think this is a good default, but what if you don’t want to see these 404 errors?
There are 2 options to solve this:
- Through a Telemetry Processor
- Through a Telemetry Initializer
Telemetry Processor
A telemetry processor gives you direct control over what is included or excluded from the telemetry stream.
public class 404TelemetryFilter : ITelemetryProcessor | |
{ | |
private readonly ITelemetryProcessor _next; | |
public 404TelemetryFilter(ITelemetryProcessor next) | |
{ | |
_next = next; | |
} | |
public void Process(ITelemetry item) | |
{ | |
// Ignore item if we got a 404 response, this is often expected | |
if (item is RequestTelemetry reqTel) | |
if (reqTel.ResponseCode.Equals("404", StringComparison.OrdinalIgnoreCase)) | |
return; | |
_next.Process(item); | |
} | |
} |
We can register our new TelemetryProcessor
by using the AddApplicationInsightsTelemetryProcessor
extension method on IServiceCollection
, as shown below:
public void ConfigureServices(IServiceCollection services) | |
{ | |
services.AddApplicationInsightsTelemetry(); | |
services.AddApplicationInsightsTelemetryProcessor<404TelemetryFilter>(); | |
} |
Telemetry Initializer
Telemetry initializers allow you to enrich telemetry with additional information and/or to override telemetry properties set by the standard telemetry modules. By default, any request with a response code >= 400 is flagged as failed. But if we want to treat a 404 as a success, we can provide a telemetry initializer that sets the Success property:
public class 404TelemetryInitializer : ITelemetryInitializer | |
{ | |
public void Initialize(ITelemetry telemetry) | |
{ | |
var requestTelemetry = telemetry as RequestTelemetry; | |
// Is this a TrackRequest() ? | |
if (requestTelemetry == null) return; | |
bool parsed = Int32.TryParse(requestTelemetry.ResponseCode, out code); | |
if (!parsed) return; | |
if (code == 404 ) | |
{ | |
// If we set the Success property, the SDK won't change it: | |
requestTelemetry.Success = true; | |
} | |
} | |
} |
We can register the TelemetryInitializer in our Startup.cs:
public void ConfigureServices(IServiceCollection services) | |
{ | |
services.AddSingleton<ITelemetryInitializer, 404TelemetryInitializer>(); | |
} |
Advantage of the Telemetry Initializer is that we still log the 404 event but no longer as an error.
More information: https://docs.microsoft.com/en-us/azure/azure-monitor/app/api-filtering-sampling