How to enable Application insights for static website which is hosting in Azure storage account?

172 views Asked by At

I have an Angular application and it is deployed as a static website in Azure storage account. I use the following code to set up Application Insights in my app. After deployment, I can not see any trace data in my App Insights workspace.

  loadApplicationInsights() {
    this._initAppInsights();
    this._appInsights?.loadAppInsights();
  }

  logException(exception: Error, severityLevel?: number) {
    this._appInsights?.trackException({ exception: exception, severityLevel: severityLevel });
  }

  logTrace(message: string, properties?: { [key: string]: any }) {
    this._appInsights?.trackTrace({ message: message}, properties);
  }
  private _initAppInsights() {
    const { enableInsights, instrumentationKey } = this._appConfig.envConfig.applicationInsights || { enableInsights: false, instrumentationKey: null };

    if (enableInsights && instrumentationKey){
      this._appInsights = new ApplicationInsights({
        config: {
          instrumentationKey,
          enableAutoRouteTracking: true,
        }
      });

   }
  }

This setting works when I deploy the app to Azure web app. What needs to be adjusted for static website hosting in Azure storage account?

1

There are 1 answers

0
Suresh Chikkam On

Firstly, Install npm install --save @microsoft/applicationinsights-web in your Angular application.

enter image description here

  • Then, configure application insights. You can do this in your Angular service or component.
import { Injectable } from '@angular/core';
import { ApplicationInsights } from '@microsoft/applicationinsights-web';

@Injectable({
  providedIn: 'root',
})
export class TelemetryService {
  private appInsights: ApplicationInsights;

  constructor() {
    this.appInsights = new ApplicationInsights({
      config: {
        instrumentationKey: 'YOUR_INSTRUMENTATION_KEY',
        enableAutoRouteTracking: true,
      },
    });
    this.appInsights.loadAppInsights();
  }

  logTrace(message: string, properties?: { [key: string]: any }) {
    this.appInsights.trackTrace({ message: message }, properties);
  }

  // Add other telemetry methods as needed (e.g., logException).
}
  • Check the code that initializes Application Insights is executed when the application loads.

enter image description here

  • Then Deploy the application to the Azure Storage Account as a static website.

enter image description here

Configure CORS rules to allow requests from your static website's domain. This is crucial for Application Insights to send telemetry data to the correct endpoint.