Is it possible to disable application insights tracking in a specific web api controller?

Viewed 1520

I have an Asp.net core web api project and i've added the simplest configuration of application insights in Startup.cs file.

 services.AddApplicationInsightsTelemetry();

Everything is fine and the data is sent to Azure correctly, but now I need to stop tracking data from a specific controller because it makes a request to an external api and when it fails i'm able to control the flow but i dont want to see those error un application insights portal.

2 Answers

You can use telemetry processor to filter out the data from the specified controller, sample code like below:

public class CustomControllerFilter : ITelemetryProcessor
{
    private ITelemetryProcessor Next { get; set; }

    public CustomControllerFilter(ITelemetryProcessor next)
    {
        this.Next = next;
    }
    public void Process(ITelemetry item)
    {
        RequestTelemetry telemetry = item as RequestTelemetry;

        if (telemetry != null)
        {
            //the test controller
            if (telemetry.Url.AbsoluteUri.Contains("/test/"))
            {
                return;
            }
        }


        this.Next.Process(item);
    }
}

Then register it in Startup.cs -> ConfigureServices method:

    public void ConfigureServices(IServiceCollection services)
    {
        //other code
        services.AddApplicationInsightsTelemetry();

        //register it here
        services.AddApplicationInsightsTelemetryProcessor<CustomControllerFilter>();
    }

You can create a method to disable it and call on the controller. This method would include:

TelemetryConfiguration.Active.DisableTelemetry = true;

Another option would be modifying appsettings.json to control the logging done by ApplicationInsights. Something like the following in appsettings.json ensure Applicationinsights only sends traces for logs with severity >= Warning.

{
  "Logging": {
    "IncludeScopes": false,
    "Debug": {
      "LogLevel": {
        "Default": "Trace"
      }
    },
    "Console": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "ApplicationInsights": {
      "LogLevel": {
        "Default": "Warning"
      }
    }
  }
}
Related