132

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

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Alberto Rivelli
  • 1,953
  • 2
  • 15
  • 19
  • 1
    For anyone landing on this question in 2021: sort the answers by active, NOT votes, to get up-to-date information. – Ian Kemp Sep 21 '21 at 12:04

16 Answers16

84

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

#if DEBUG
            TelemetryConfiguration.Active.DisableTelemetry = true;
#endif
Abhijit Jana
  • 940
  • 1
  • 5
  • 9
  • I tried adding this statement just before `WindowsAppInitializer.InitializeAsync();` (I also tried after it) but the visual studio application insights events counter increased. I was not able to see if this session was effectively recorded in the azure portal because there are too many sessions and users. I'll try during the night. – Alberto Rivelli Aug 18 '15 at 21:26
  • Alberto, I tested like this - 'code' public sealed partial class MainPage : Page { TelemetryClient telemetry; public MainPage() { this.InitializeComponent(); #if DEBUG TelemetryConfiguration.Active.DisableTelemetry = true; #endif telemetry = new TelemetryClient(); } private void button_Click(object sender, RoutedEventArgs e) { telemetry.TrackEvent("Event Custom"); } 'code' .. and seems to be working. i will try some other pages as well. will keep you updated – Abhijit Jana Aug 19 '15 at 03:47
  • Also, from the Visual Studio itself, you can check if the telemetry events are sent or not . I just posted this yestarday [How to get number of Application Insights events from Visual Studio 2015](http://bit.ly/1JhfHum) – Abhijit Jana Aug 19 '15 at 03:59
  • That's what I wrote, the visual studio events counter increased. – Alberto Rivelli Aug 19 '15 at 08:27
  • Can you please debug and see if 'TelemetryConfiguration.Active' has the same instrumentationKey. Just wanted to check if it's is picking up right TelemetryConfiguration. – Abhijit Jana Aug 19 '15 at 09:00
  • `TelemetryConfiguration.Active.InstrumentationKey` is empty. Setting the key in code and then setting `DisableTelemetry = true` does not work. Even trackclient has an emtpy InstrumentationKey, because I think the libraries are reading the key from the config file. That's why not copying the config file, blocks events from being sent. – Alberto Rivelli Aug 19 '15 at 12:23
  • I like this solution more – Roboblob Oct 30 '16 at 20:09
  • 5
    Even with DisableTelemetry set to true and an empty instrumentation key, the telemetry modules will keep collecting data. The data won't be sent, but it will be collected. See this issue logged against App Insights: github.com/Microsoft/ApplicationInsights-dotnet/issues/397 If you want to disable the debut output, you can follow the steps found at github.com/Microsoft/ApplicationInsights-dotnet/issues/310 – Guillaume LaHaye Jan 17 '17 at 19:24
  • `TelemetryConfiguration` isn't defined. – Meekohi Oct 16 '20 at 17:31
72

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.

Alexander Schmidt
  • 5,631
  • 4
  • 39
  • 79
  • 2
    We usually deploy the DEBUG config to the staging and RELEASE config to the production. Both of them can have OWN telemetry enabled. So your change will disable the telemetry for the staging environment. – SerjG Aug 15 '16 at 11:59
  • 2
    @Sergey I would suggest to define a single configuration and defining a STAGING variable there. Thus you can better distinguish between debugging locally. Another option would be to define a new symbol LOCAL and replace it in the `Conditional`-attribute. – Alexander Schmidt Aug 15 '16 at 16:36
  • typically we have different DB connection strings, storage accounts and other settings for STAG and PROD (like FB app id, SendGrid account, app settings, etc). Moreover - locally we have Azure storage emulator and local SQL Express. So there is no way to work with a single configuration. We need 3 different configurations and the local one should have the disabled telemetry. – SerjG Aug 16 '16 at 21:03
  • You can still define a custom symbol on more than one of your configs. Then instead of using Conditional("DEBUG"), you could do Conditional("WHATEVER"). Alternatively you could grab a value from appSettings and use transforms to blow it away in non-local environments. – joelmdev Jan 18 '18 at 02:30
  • `TelemetryConfiguration` isn't defined. – Meekohi Oct 16 '20 at 17:31
  • 1
    This worked for me running VS 2019 targetting the .NET 4.8 framework. Note: The built in disable option in VS 2019 did not, as it only targets Asp.Net Core projects. – Cale Sweeney Aug 30 '22 at 13:57
  • I'm seeing this as deprecated since June 2019. For other's that see the warning the link is: https://github.com/microsoft/ApplicationInsights-dotnet/issues/1152 – John Warlow Dec 09 '22 at 13:00
50

NOTE: This option only existed in Visual Studio 2019

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

Siva Chamarthi
  • 585
  • 5
  • 9
  • 4
    This did not work for me. It looks like it should, but for some reason my debug output is still flooding with these pointless messages. – Ross Brasseaux Nov 12 '20 at 16:05
  • 1
    does not work.... The way I did is by adding services.AddApplicationInsightsTelemetry(... only if not dev environment. – zak Oct 12 '21 at 16:08
  • 6
    That option doesn't even exist anymore – HackSlash Apr 20 '22 at 17:53
  • The disable option noted above exists in VS 2019. But pay attention to what framework you are using. You can check your TargetFrameworkVersion in the .csproj file . I am using .NET 4.8, and it will not work for that. This toggle is specific to Asp.Net Core. – Cale Sweeney Aug 30 '22 at 13:56
31

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.

alv
  • 1,037
  • 12
  • 15
24

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

dasch88
  • 999
  • 10
  • 13
Alberto Rivelli
  • 1,953
  • 2
  • 15
  • 19
  • 1
    See [this blog](http://codery.co.uk/blog/turn-off-application-insights-for-your-dev-environment/) how to use this with a separate `ApplicationInsights.Debug/Release.config` – Yahoo Serious Sep 04 '18 at 16:11
19

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
    }
}
Ian Kemp
  • 28,293
  • 19
  • 112
  • 138
  • @IanKemp How do you get access to `TelemetryConfiguration` in a [.NET 6 Minimal API](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis?view=aspnetcore-6.0)? – Kristoffer Jälén May 18 '22 at 12:49
  • 2
    @KristofferJälén I don't believe that you can. That is the massive drawback with the minimal API template/feature and exactly why I avoid it like the plague: for extremely simple and standard things it's fine, but as soon as you actually need even the slightest amount of complexity or deviation from the norm, you are up the creek with no paddle. In my experience the only thing this template does is waste time when you inevitably have to rework your code to use the proper syntax. – Ian Kemp May 18 '22 at 14:13
15

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;
    }
}
SerjG
  • 3,325
  • 3
  • 30
  • 30
12

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;
chris31389
  • 8,414
  • 7
  • 55
  • 66
11

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

Josh
  • 4,009
  • 2
  • 31
  • 46
9

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

Extensibility.Implementation.TelemetryDebugWriter.IsTracingDisabled = True
Peter Jarrett
  • 115
  • 1
  • 10
9

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.

saluce
  • 13,035
  • 3
  • 50
  • 67
  • Nope... didn't make any difference for me (with ASP.Net Core 2.1). Still get a mountain of "Application Insights Telemetry" messages in the Output window. – Mike Gledhill Aug 22 '18 at 13:12
6

Microsoft.ApplicationInsights.AspNetCore Version 2.1

services.AddApplicationInsightsTelemetry(options =>
{
    options.EnableDebugLogger = false;
});
JJS
  • 6,431
  • 1
  • 54
  • 70
  • Is this supposed to hide the `Application Insights Telemetry (unconfigured)` messages from Debug panel in Visual Studio - because if so it doesn't seem to work :-( – Simon_Weaver Jan 10 '18 at 07:11
  • 3
    I'm not sure what that kind of message is. I believe you're looking for `TelemetryDebugWriter.IsTracingDisabled = true;` to remove those. – JJS Jan 11 '18 at 15:01
4

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://learn.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://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-5.0

rjacobsen0
  • 1,287
  • 13
  • 25
2
         public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            #region Disable Application Insights debug informations
#if DEBUG
            TelemetryConfiguration.Active.DisableTelemetry = true;
            TelemetryDebugWriter.IsTracingDisabled = true;
#endif
            #endregion
//...
}
SZL
  • 805
  • 8
  • 12
1

Since .NET Core 3.1:

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

var telemetryClient = new TelemetryClient(telemetryConfiguration);   // Use this instance
TelemetryDebugWriter.IsTracingDisabled = true;
silkfire
  • 24,585
  • 15
  • 82
  • 105
  • 2
    Here's the docs for doing this, including getting the TelemetryConfiguration via dependency injection: https://learn.microsoft.com/en-us/azure/azure-monitor/app/asp-net-core#disable-telemetry-dynamically – Noah Stahl Apr 03 '20 at 00:15
1

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.

Grigory Zhadko
  • 1,484
  • 1
  • 19
  • 33
Amber
  • 39
  • 1
  • 3
  • I think is almost the best solution. You could put the configuration in appSettings.Development.json. This way no code is needed when deploying to Azure. – Marcel Gelijk Mar 09 '22 at 14:37