Disable application insights in debug

C#Azure Application-Insights

C# Problem Overview


How can I disable application insights automatically when using a debug configuration and enable it only on release?
Is it possible to do this without creating another instrumentation key only for debug?

I have trackevent statements scattered all over the code, enclosing them inside a debug preprocessor check is not an ideal solution.

My current solution is to set the Build Action of the ApplicationInsights.config file to None so that it's not copied to the project's output directory, but this isn't a process that can be automated based on the active build configuration.

There is a Developer Mode but needs to be changed manually (if it was possible to conditionally set the config file, emptying the instrumentationkey solved problem as well). See http://apmtips.com/blog/2015/02/02/developer-mode/

Reference: http://blogs.msdn.com/b/visualstudioalm/archive/2015/01/07/application-insights-support-for-multiple-environments-stamps-and-app-versions.aspx

C# Solutions


Solution 1 - C#

You can try to use TelemetryConfiguration.DisableTelemetry Property Something like this way..

#if DEBUG
            TelemetryConfiguration.Active.DisableTelemetry = true;
#endif

Solution 2 - C#

As an addition to the other solutions I would suggest to add the following let's say to the Global.asax:

protected void Application_Start()
{    
    DisableApplicationInsightsOnDebug();
    // do the other stuff
}

/// <summary>
/// Disables the application insights locally.
/// </summary>
[Conditional("DEBUG")]
private static void DisableApplicationInsightsOnDebug()
{
    TelemetryConfiguration.Active.DisableTelemetry = true;
}

The advantage of this is, that it needs no change to the configs and it works better with some tools like ReSharper which will understand it better than #-directives.

Solution 3 - C#

For ASP.NET Core projects the App Insights are ON by default, which actually logs a ton of info into debug window.

To disable it go to "TOOLS --> Options --> Projects and Solutions --> Web Projects" and check "Disable local Application Insights for Asp.Net Core web projects."

Below is the image for disabling local app insights.

Image

For more info on the issue you can see the official github issue here

Solution 4 - C#

Running an ASP.NET Core 2.1 web application with Visual Studio 2017 (15.9.2) the "Disable local Application Insights for Asp.Net Core web projects" did not clear up the output in my Debug window.

However adding the following to Configure() in Startup.cs did the job;

if (_env.IsDevelopment())
{
	app.UseDeveloperExceptionPage();
	TelemetryConfiguration.Active.DisableTelemetry = true;
	TelemetryDebugWriter.IsTracingDisabled = true;
}

Note that the IsTracingDisabled was the key solution, but I left in DisableTelemetry for good measure! Plus having both lines next to one another is helpful when searching for similar references between .NET Framework & .NET Core projects in the same solution.

Solution 5 - C#

As explained in the question not deploying or deploying an ApplicationInsights.config without <instrumentationkey>key</instrumentationkey> block events from being generated. You can then put the instrumentation key in code (only on release in my case)

#if !DEBUG
    Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.Active.InstrumentationKey = "instrumentation key";
#endif

Every TelemetryClient created after this call will have the correct key and will track events so you don't have to change the code in all places. Not calling the method above or leaving the parameter empty will block events because there isn't a key configured.

Basically the ApplicationInsights.config file overrides any code that set the instrumentation key, removing the <instrumentationkey>key</instrumentationkey> inside it will let you use code to configure the key. If you remove the file completely it doesn't work.

Here is the confirm: "If you want to set the key dynamically - for example if you want to send results from your application to different resources - you can omit the key from the configuration file, and set it in code instead."

Reference: https://azure.microsoft.com/en-us/documentation/articles/app-insights-configuration-with-applicationinsights-config/#_instrumentationkey

Solution 6 - C#

I have decided to use both approaches. I have moved the InstrumentationKey to the Web.config and it will be replaced by the transformation from Web.Release.config or Web.Debug.config. (don't forget to remove it from the ApplicationInsights.config file). Then I have called this method from the Application_Start()

public static void RegisterTelemetryInstrumentationKey()
{
	if (string.IsNullOrWhiteSpace(WebConfigurationManager.AppSettings["TelemetryInstrumentationKey"])
	{
		TelemetryConfiguration.Active.DisableTelemetry = true;
	}
	else
	{
		TelemetryConfiguration.Active.InstrumentationKey = AppSettings.TelemetryInstrumentationKey;
	}
}

Solution 7 - C#

As of ASP.NET Core 3.1:

public void Configure(IApplicationBuilder app, IHostingEnvironment env,
    TelemetryConfiguration configuration)
{
    configuration.DisableTelemetry = true;
}
TelemetryDebugWriter.IsTracingDisabled = true;

(the above can be called from anywhere, but the sooner in your application's lifecycle, the better).

Both can be used together to suppress all Application Insights activity in your code. I guard with an #if DEBUG directive to ensure that AppInsights does nothing on my local machine, but does emit events when published to our dev server in the Azure cloud:

public void Configure(IApplicationBuilder app, IHostingEnvironment env,
    TelemetryConfiguration configuration)
{
    if (env.IsDevelopment())
    {
#if DEBUG
        configuration.DisableTelemetry = true;

        TelemetryDebugWriter.IsTracingDisabled = true;
#endif
    }
}

Solution 8 - C#

I've just had the same issue.

We wanted to control the setting in the web.config so added a DisableAITelemetry key within our app settings:

  <appSettings>
    <add key="DisableAITelemetry" value="true" />
  </appSettings>

With live and demo builds, we won't include a value (so that it defaults to false).

We could then solve it by adding this:

bool disable;
string disableAiTelemetry = ConfigurationManager.AppSettings["DisableAITelemetry"];
bool.TryParse(disableAiTelemetry, out disable);
TelemetryConfiguration.Active.DisableTelemetry = disable;

Solution 9 - C#

Slightly different play on some of the other solutions. Put this in your global.asax:

Microsoft.ApplicationInsights.Extensibility.Implementation.TelemetryDebugWriter.IsTracingDisabled = Debugger.IsAttached;

It will turn off app insights debug output when running under the debugger, but allow it under Ctrl+F5 scenarios and debug builds published to test servers

Solution 10 - C#

We've found the easiest way to prevent it from tracing into the Debug log is as simple as:

Extensibility.Implementation.TelemetryDebugWriter.IsTracingDisabled = True

Solution 11 - C#

In an ASP.NET Core application, you can add the following to the Startus.cs to turn off Application Insights in the Development environment:

if (env.IsDevelopment()) {
    TelemetryConfiguration.Active.DisableTelemetry = true;
}

Add this to the constructor, right after the builder.AddApplicationInsightsSettings(); command and you'll no longer see AI logs clogging up your debug console.

Solution 12 - C#

Microsoft.ApplicationInsights.AspNetCore Version 2.1

services.AddApplicationInsightsTelemetry(options =>
{
    options.EnableDebugLogger = false;
});

Solution 13 - C#

         public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            #region Disable Application Insights debug informations
#if DEBUG
            TelemetryConfiguration.Active.DisableTelemetry = true;
            TelemetryDebugWriter.IsTracingDisabled = true;
#endif
            #endregion
//...
}

Solution 14 - C#

The solution suggested above has been deprecated (reference: https://github.com/microsoft/applicationinsights-dotnet/issues/1152). In dotnet core the new way to dynamically disable telemetry is this:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddApplicationInsightsTelemetry();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, TelemetryConfiguration configuration)
    {
        configuration.DisableTelemetry = true;
        ...
    }

(reference: https://docs.microsoft.com/en-us/azure/azure-monitor/app/asp-net-core#disable-telemetry-dynamically)

And if you want to disable telemetry in a custom WebApplicationFactory (when doing integration tests) you can do this:

public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.ConfigureServices((context, services) =>
        {
            // Disable application insights during testing.
            services.Configure<TelemetryConfiguration>(
                (telemetryConfig) => {
                    telemetryConfig.DisableTelemetry = true;
                });
        });
        base.ConfigureWebHost(builder);
    }
}

For more context about integration testing see https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-5.0

Solution 15 - C#

Since .NET Core 3.1:

var telemetryConfiguration = TelemetryConfiguration.CreateDefault();
telemetryConfiguration.DisableTelemetry = true;

var telemetryClient = new TelemetryClient(telemetryConfiguration);   // Use this instance
TelemetryDebugWriter.IsTracingDisabled = true;

Solution 16 - C#

We can modify the file “appsetting.json” and add the following attributes

"ApplicationInsights": {
	"EnableRequestTrackingTelemetryModule": false,
	"EnableEventCounterCollectionModule": false,
	"EnableDependencyTrackingTelemetryModule": false,
	"EnablePerformanceCounterCollectionModule": false,
	"EnableDiagnosticsTelemetryModule": false
  }

More information you can find here.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlberto RivelliView Question on Stackoverflow
Solution 1 - C#Abhijit JanaView Answer on Stackoverflow
Solution 2 - C#Alexander SchmidtView Answer on Stackoverflow
Solution 3 - C#Siva ChamarthiView Answer on Stackoverflow
Solution 4 - C#alvView Answer on Stackoverflow
Solution 5 - C#Alberto RivelliView Answer on Stackoverflow
Solution 6 - C#SerjGView Answer on Stackoverflow
Solution 7 - C#Ian KempView Answer on Stackoverflow
Solution 8 - C#chris31389View Answer on Stackoverflow
Solution 9 - C#JoshView Answer on Stackoverflow
Solution 10 - C#Peter JarrettView Answer on Stackoverflow
Solution 11 - C#saluceView Answer on Stackoverflow
Solution 12 - C#JJSView Answer on Stackoverflow
Solution 13 - C#SZLView Answer on Stackoverflow
Solution 14 - C#rjacobsen0View Answer on Stackoverflow
Solution 15 - C#silkfireView Answer on Stackoverflow
Solution 16 - C#AmberView Answer on Stackoverflow