admin管理员组

文章数量:1406018

I'm experiencing an issue with the Microsoft Application Insights SDK for JavaScript that was closed/fixed awhile ago:

I created a brand new Angular app using the Angular CLI. Then I made these changes, following this article.

Added a monitoring service:

import {Injectable} from '@angular/core';
import {AppInsights} from 'applicationinsights-js';

@Injectable()
export class MonitoringService {
  private config: Microsoft.ApplicationInsights.IConfig = {
    instrumentationKey: 'KEY_GOES_HERE',
    enableDebug: true,
    verboseLogging: true
  };

  constructor() {
    if (!AppInsights.config) {
      AppInsights.downloadAndSetup(this.config);
    }
  }

  logPageView(name?: string, url?: string, properties?: any, measurements?: any, duration?: number) {
    AppInsights.trackPageView(name, url, properties, measurements, duration);
  }

  logEvent(name: string, properties?: any, measurements?: any) {
    AppInsights.trackEvent(name, properties, measurements);
  }

  trackException(exception: Error) {
    AppInsights.trackException(exception);
  }
}

Added it to my appponent.ts:

import {Component, OnInit} from '@angular/core';
import {MonitoringService} from './monitoring.service';

@Component({
  selector: 'app-root',
  templateUrl: './appponent.html',
  styleUrls: ['./appponent.css'],
  providers: [MonitoringService]
})
export class AppComponent implements OnInit {
  title = 'app works!';

  constructor(private monitoringService: MonitoringService) { }

  ngOnInit() {
      this.monitoringService.logPageView();
  }

  throwAnException() {
      this.monitoringService.trackException(new Error('manually track exception'));
      throw 'this should appear in app insights'; // but it doesn't
  }
}

Made a simple button for throwing the exception in my appponent.html:

<h1>
  {{title}}
</h1>
<div (click)="throwAnException()">Click to throw an exception</div>

Logging a page view works, as does tracking the exception by explicitly calling trackException. From reading the documentation and various articles, I was under the impression that uncaught exceptions would always automatically get sent to Application Insights. However, I am not seeing any of those show up in the portal.

What could I be missing here?

Using these versions:

applicationinsights-js: 1.0.11
@types/applicationinsights-js: 1.0.4

I'm experiencing an issue with the Microsoft Application Insights SDK for JavaScript that was closed/fixed awhile ago: https://github./Microsoft/ApplicationInsights-JS/issues/282

I created a brand new Angular app using the Angular CLI. Then I made these changes, following this article.

Added a monitoring service:

import {Injectable} from '@angular/core';
import {AppInsights} from 'applicationinsights-js';

@Injectable()
export class MonitoringService {
  private config: Microsoft.ApplicationInsights.IConfig = {
    instrumentationKey: 'KEY_GOES_HERE',
    enableDebug: true,
    verboseLogging: true
  };

  constructor() {
    if (!AppInsights.config) {
      AppInsights.downloadAndSetup(this.config);
    }
  }

  logPageView(name?: string, url?: string, properties?: any, measurements?: any, duration?: number) {
    AppInsights.trackPageView(name, url, properties, measurements, duration);
  }

  logEvent(name: string, properties?: any, measurements?: any) {
    AppInsights.trackEvent(name, properties, measurements);
  }

  trackException(exception: Error) {
    AppInsights.trackException(exception);
  }
}

Added it to my app.ponent.ts:

import {Component, OnInit} from '@angular/core';
import {MonitoringService} from './monitoring.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.ponent.html',
  styleUrls: ['./app.ponent.css'],
  providers: [MonitoringService]
})
export class AppComponent implements OnInit {
  title = 'app works!';

  constructor(private monitoringService: MonitoringService) { }

  ngOnInit() {
      this.monitoringService.logPageView();
  }

  throwAnException() {
      this.monitoringService.trackException(new Error('manually track exception'));
      throw 'this should appear in app insights'; // but it doesn't
  }
}

Made a simple button for throwing the exception in my app.ponent.html:

<h1>
  {{title}}
</h1>
<div (click)="throwAnException()">Click to throw an exception</div>

Logging a page view works, as does tracking the exception by explicitly calling trackException. From reading the documentation and various articles, I was under the impression that uncaught exceptions would always automatically get sent to Application Insights. However, I am not seeing any of those show up in the portal.

What could I be missing here?

Using these versions:

applicationinsights-js: 1.0.11
@types/applicationinsights-js: 1.0.4
Share Improve this question edited Aug 23, 2017 at 0:26 chinaowl asked Aug 22, 2017 at 22:18 chinaowlchinaowl 5325 silver badges15 bronze badges 2
  • 1 looks like you also opened this as an issue on our github as well: github./Microsoft/ApplicationInsights-JS/issues/505 i was going to post that as a suggestion :) – John Gardner Commented Aug 22, 2017 at 23:28
  • Yup, that was me! – chinaowl Commented Aug 23, 2017 at 0:27
Add a ment  | 

2 Answers 2

Reset to default 4

I've struggles with the same thing and here is the things you need to know to hack it through:

What is happenning?

Angular catches all the exceptions (swallows them!) and just logs them inside console. I have not seen this behavior being explicitly told in any documentation, but I've tested this in code, so trust me. On the other hand only uncaught exceptions are autocollected! (see here). For collecting caught exceptions ( as is mostly the case when using angular framework) you have to call trackException() explicitly in your code.

How to solve it :

We will implement a service (called MonitoringService in code below) to municate with azure application insights. Then we will tell angular to use this service to log exceptions in azure ai, instead of logging just into browser console, by extending ErrorHandler class.

1) implement MonitoringService:

We'll be using a service named MonitoringService to municate with azure application insights. Implement that service like this:

import { Injectable } from "@angular/core";
import { ApplicationInsights } from "@microsoft/applicationinsights-web";
import { environment } from "@env/environment";

@Injectable({
  providedIn: "root",
})
export class MonitoringService {
  private appInsights: ApplicationInsights;
  constructor() {}
  startMonitoring(): void {
    this.appInsights = new ApplicationInsights({
      config: {
        instrumentationKey: environment.appInsights.instrumentationKey,
      },
    });
    this.appInsights.loadAppInsights();
    this.appInsights.trackPageView();
  }  

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

startMonitoring() should be called on app start up.

2) start monitoring on app start up:

Angular projects mostly have a app.ponent.ts file which belongs to the root module and is bootstrapped/initialized as the first ponent. By the term "on app start up", I actually mean the time this ponent is being initialized.
We'll create an instance of MonitoringService and have it start its job:

import { Component } from '@angular/core';
import { MonitoringService } from 'services/monitoring.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.ponent.html',
  styleUrls: ['./app.ponent.scss'],
})
export class AppComponent {
  constructor(
    private monitoringService: MonitoringService
  ) {
    this.monitoringService.startMonitoring();
  }
}

3) Log errors into application insights, before they are swallowed by framework:

Extend ErrorHandler class in your project. This class is actually a hook for centralized exception handling in angular spa. Use this hook, to log exceptions before they are swallowed by framework:

import { Injectable, ErrorHandler } from '@angular/core';
import { MonitoringService } from './monitoring.service';

@Injectable({
  providedIn: 'root'
})
export class GlobalErrorHandlerService implements ErrorHandler {

  constructor(private monitoringService: MonitoringService) { }
  handleError(error: any): void {
    console.error(error);
    this.monitoringService.logException(error);
  }
}

4) Register the ErrorHandler with Angular:

In the AppModule make sure to register this Handler with Angular:

@NgModule({
  providers: [{provide: ErrorHandler, useClass: GlobalErrorHandlerService}]
})
class AppModule {}

I don't think AppInsights has any knowledge of Angular and the other way around, Angular doesn't know about app insights so you'll probably have to add this in by yourself using a custom ErrorHandler. Have a look at the ErrorHandler official documentation. If you put your this.monitoringService.trackException call in the handleError there it should work fine.

本文标签: javascriptApplication Insights does not track unhandled browser exceptions in Angular appStack Overflow