How to load and unload Azure App Insights for web pages in JavaScript

Viewed 855

I have followed this guide and this guide to add Azure App Insights to our Angular application. It works great but the problem I am having is how can we start/load and stop/unload tracking of the insights conditionally?

Basically, we have a toggle in our application that allows the user to turn on collection of data and Application Insights should be analyzing and collecting the data. Once the user turns this toggle off, it should stop analyzing and tracking.

It seems once we call this.appInsights.loadAppInsights(), there is no way to unlatch/unload/stop listening. If there is a way to unlatch/unload/stop listening, please let me know.

Thanks.

2 Answers

You can refer to the doc Disabling telemetry.

For example, if you want to unload app insights in javascript, use the code below:

telemetry.config.disableAppInsights = true;

I ended up creating a common service related to everything with AppInsights inspired from here.

import { AngularPlugin, AngularPluginService } from '@microsoft/applicationinsights-angularplugin-js';
import {
  ApplicationInsights,
  IEventTelemetry,
  IExceptionTelemetry
 } from '@microsoft/applicationinsights-web';
....

export class ApplicationInsightService {
  private appInsights: ApplicationInsights;

  constructor(private router: Router, private angularPluginService: AngularPluginService) {
    const angularPlugin = new AngularPlugin();
    this.angularPluginService.init(angularPlugin, this.router);
    this.appInsights = new ApplicationInsights({ config: {
      instrumentationKey: 'Your key here',
      extensions: [angularPlugin],
      extensionConfig: {
        [angularPlugin.identifier]: { router: this.router },
      }
    }});
    this.appInsights.loadAppInsights();
    this.appInsights.trackPageView();
  }

  setUserId(userId: string) {
    this.appInsights.setAuthenticatedUserContext(userId);
  }

  clearUserId() {
    this.appInsights.clearAuthenticatedUserContext();
  }

  logPageView(name?: string, uri?: string) {
    this.appInsights.trackPageView({ name, uri });
  }

  logEvent(event: IEventTelemetry, customProperties: { [key: string]: any }) {
    this.appInsights.trackEvent(event, customProperties);
  }

  trackError(exception: Error) {
    let telemetry = {
      exception,
    } as IExceptionTelemetry;
    this.appInsights.trackException(telemetry);
  }

  stopTelemetry() { // !! this is how you stop tracking
    this.appInsights.config.disableTelemetry = true;
  }

  startTelemetry() { // !! this is how you start/re-start it
    this.appInsights.config.disableTelemetry = false;
  }
}

The JavaScript part of the documentation was not helpful because those methods/properties didn't exist but the C# documentation helped and it seems to be similar to that.

Related