Filtering Application Insights telemetry using a ITelemetryProcessor

Application Insights is a wonderful tool. Especially when you have a microservice or multi-application environment and you need one place for all the logs and metrics. But it’s not free, and the costs can run wild if you are not careful.

Although the message logging usually is the most expensive cost, remote dependencies and requests can take up a lot of the costs too.

You can suppress the telemetry data by using a ITelemetryProcessor. The ITelemetryProcessor processes the telemetry information before it is send to Application Insights, and can be useful in many situations, including as a filter.

Take a look at this graph, the red part are my dependencies, and you can see the drop in tracking after the filter was applied:

Application Insights Estimated Costs

Application Insights Estimated Costs

This is an example on the dependency telemetry filter that will exclude all successful dependencies to be tracked, but allow all those that fails:

using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility;

namespace MyCode
{
  public class DependencyTelemetryFilter : ITelemetryProcessor
  {
    private readonly ITelemetryProcessor _nextProcessor;

    public DependencyTelemetryFilter(ITelemetryProcessor nextProcessor)
    {
      _nextProcessor = nextProcessor;
    }
    
    public void Process(ITelemetry telemetry)
    {
      if (telemetry is DependencyTelemetry dependencyTelemetry)
      {
        if (dependencyTelemetry.Success == true)
        {
          return;
        }
      }

      _nextProcessor.Process(telemetry);
    }
  }
}

To add the filter, simply call the AddApplicationInsightsTelemetryProcessor method in your startup code:

private void ConfigureApplicationInsights(IServiceCollection services)
{
  services.AddApplicationInsightsTelemetryProcessor<DependencyTelemetryFilter>();
}

MORE TO READ:

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in .net, .NET Core, General .NET, Microsoft Azure and tagged , , . Bookmark the permalink.

1 Response to Filtering Application Insights telemetry using a ITelemetryProcessor

  1. Pingback: C# Log to Application Insights and File from your .NET 6 Application | Brian Pedersen's Sitecore and .NET Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.