Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add trackMetric method for Angular plugin #1359

Merged
merged 7 commits into from
Sep 4, 2020
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 40 additions & 2 deletions extensions/applicationinsights-angularplugin-js/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@

Angular Plugin for the Application Insights Javascript SDK, enables the following:

> ***Note:*** Angular plugin is NOT es3 compatible

- Tracking of router changes
- Angular components usage statistics

Angular Plugin for the Application Insights Javascript SDK

Expand All @@ -19,10 +22,11 @@ npm install @microsoft/applicationinsights-angularplugin-js

## Basic Usage

Set up an instance of Application Insights in the entry component in your app:
```js
import { Component, OnInit } from '@angular/core';
import { ApplicationInsights } from '@microsoft/applicationinsights-web';
import { AngularPlugin } from '@microsoft/applicationinsights-angularplugin-js';
import { AngularPlugin, AngularPluginService } from '@microsoft/applicationinsights-angularplugin-js';
import { Router } from '@angular/router';

@Component({
Expand All @@ -33,9 +37,11 @@ import { Router } from '@angular/router';
export class AppComponent implements OnInit {
private appInsights;
constructor(
private router: Router
private router: Router,
private angularPluginService: AngularPluginService
){
var angularPlugin = new AngularPlugin();
this.angularPluginService.init(angularPlugin, this.router);
this.appInsights = new ApplicationInsights({ config: {
instrumentationKey: 'YOUR_INSTRUMENTATION_KEY_GOES_HERE',
extensions: [angularPlugin],
Expand All @@ -52,6 +58,38 @@ export class AppComponent implements OnInit {

```

If you need to use trackMetric method to track Angular component usage, add `AngularPluginService` as a provider in providers list in `app.module.ts` file:
```js
import { AngularPluginService } from '@microsoft/applicationinsights-angularplugin-js';

@NgModule({
...
providers: [ AngularPluginService ],
})
export class AppModule { }
```

Make the `trackMetric` call in the `ngOnDestroy` method in the component you want to track the lifetime with. When this component gets destroyed, it will trigger a trackMetric event sent with the time user stayed on this page, and the component name.
```js
import { Component, OnDestroy, HostListener } from '@angular/core';
import { AngularPluginService } from '@microsoft/applicationinsights-angularplugin-js';

@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnDestroy {

constructor(private angularPluginService: AngularPluginService) {}

@HostListener('window:beforeunload')
ngOnDestroy() {
this.angularPluginService.trackMetric();
}
}
```

## Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { AppInsightsCore, IConfiguration, ITelemetryItem, IPlugin } from '@microsoft/applicationinsights-core-js';

export class ChannelPlugin implements IPlugin {
public isFlushInvoked = false;
public isTearDownInvoked = false;
public isResumeInvoked = false;
public isPauseInvoked = false;
public identifier = 'Sender';
public priority = 1001;

constructor() {
this.processTelemetry = this._processTelemetry.bind(this);
}
public pause(): void {
this.isPauseInvoked = true;
}

public resume(): void {
this.isResumeInvoked = true;
}

public teardown(): void {
this.isTearDownInvoked = true;
}

flush(async?: boolean, callBack?: () => void): void {
this.isFlushInvoked = true;
if (callBack) {
callBack();
}
}

public processTelemetry(env: ITelemetryItem) { }

setNextPlugin(next: any) {
// no next setup
}

public initialize = (config: IConfiguration, core: AppInsightsCore, plugin: IPlugin[]) => {
}

private _processTelemetry(env: ITelemetryItem) {
}
}

export const analyticsExtension = {
initialize: (config, core, extensions) => { },
trackEvent: (event, customProperties) => { },
trackPageView: (pageView, customProperties) => { },
trackException: (exception, customProperties) => { },
trackTrace: (trace, customProperties) => { },
trackMetric: (metric, customProperties) => { },
_onerror: (exception) => { },
startTrackPage: (name) => { },
stopTrackPage: (name, properties, measurements) => { },
startTrackEvent: (name) => { },
stopTrackEvent: (name, properties, measurements) => { },
addTelemetryInitializer: (telemetryInitializer) => { },
trackPageViewPerformance: (pageViewPerformance, customProperties) => { },
processTelemetry: (env) => { },
setNextPlugin: (next) => { },
identifier: 'ApplicationInsightsAnalytics'
};

Original file line number Diff line number Diff line change
@@ -1,22 +1,34 @@
import { Component } from '@angular/core';
import { Component, HostListener, OnDestroy } from '@angular/core';
import { Routes } from '@angular/router';
import { AngularPluginService } from '../../../../src/AngularPluginService';

@Component({
template: `Search`
})
export class SearchComponent {
export class SearchComponent implements OnDestroy {
constructor(private angularPluginService: AngularPluginService){};
@HostListener('window:beforeunload')
ngOnDestroy() {
this.angularPluginService.trackMetric();
}
}

@Component({
template: `Home`
})
export class HomeComponent {
export class HomeComponent implements OnDestroy {
constructor(private angularPluginService: AngularPluginService){};
@HostListener('window:beforeunload')
ngOnDestroy() {
this.angularPluginService.trackMetric();
}
}

@Component({
template: `<router-outlet></router-outlet>`
})
export class AppComponent {
constructor(private angularPluginService: AngularPluginService){};
}

export const routes: Routes = [
Expand Down
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
import { TestBed, fakeAsync, tick } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AngularPlugin } from '@microsoft/applicationinsights-angularplugin-js';
import { AppInsightsCore, IConfiguration, DiagnosticLogger, ITelemetryItem, IPlugin } from '@microsoft/applicationinsights-core-js';
import { AppInsightsCore, IConfiguration, DiagnosticLogger } from '@microsoft/applicationinsights-core-js';
import { IPageViewTelemetry } from '@microsoft/applicationinsights-common';
import { ChannelPlugin, analyticsExtension } from './Common';

let angularPlugin: AngularPlugin;
let core: AppInsightsCore;
let angularPluginTrackPageViewSpy;
let angularPluginTrackMetricSpy;

import { Location } from '@angular/common';
import { Router } from '@angular/router';

import { HomeComponent, SearchComponent, AppComponent, routes } from './TestComponent';

describe('Router: App', () => {
describe('Angular Plugin basic events tracking tests', () => {
let location: Location;
let router: Router;
let fixture;
Expand All @@ -22,7 +24,7 @@ describe('Router: App', () => {
core = new AppInsightsCore();
core.logger = new DiagnosticLogger();
angularPlugin = new AngularPlugin();
angularPluginTrackPageViewSpy = spyOn(angularPlugin, 'trackPageView');
fixture.componentInstance.angularPluginService.init(angularPlugin, router);
}

beforeEach(() => {
Expand Down Expand Up @@ -54,34 +56,16 @@ describe('Router: App', () => {

it('Angular Plugin: router change triggers trackPageView event', fakeAsync(() => {
init();
const analyticsExtension = {
initialize: (config, core, extensions) => { },
trackEvent: (event, customProperties) => { },
trackPageView: (pageView, customProperties) => { },
trackException: (exception, customProperties) => { },
trackTrace: (trace, customProperties) => { },
trackMetric: (metric, customProperties) => { },
_onerror: (exception) => { },
startTrackPage: (name) => { },
stopTrackPage: (name, properties, measurements) => { },
startTrackEvent: (name) => { },
stopTrackEvent: (name, properties, measurements) => { },
addTelemetryInitializer: (telemetryInitializer) => { },
trackPageViewPerformance: (pageViewPerformance, customProperties) => { },
processTelemetry: (env) => { },
setNextPlugin: (next) => { },
identifier: 'ApplicationInsightsAnalytics'
};
angularPluginTrackPageViewSpy = spyOn(angularPlugin, 'trackPageView');
const channel = new ChannelPlugin();
const config: IConfiguration = {
instrumentationKey: 'instrumentation_key',
extensionConfig: {
[angularPlugin.identifier]: {
router
},
[angularPlugin.identifier]: {
router
},
}
};

core.initialize(config, [angularPlugin, analyticsExtension, channel]);

// trackPageView is called on plugin intialize
Expand All @@ -105,47 +89,34 @@ describe('Router: App', () => {
expect(angularPluginTrackPageViewSpy).toHaveBeenCalledTimes(3);
expect(angularPluginTrackPageViewSpy).toHaveBeenCalledWith({ uri: '/home' } as IPageViewTelemetry);
}));
});

class ChannelPlugin implements IPlugin {
public isFlushInvoked = false;
public isTearDownInvoked = false;
public isResumeInvoked = false;
public isPauseInvoked = false;
public identifier = 'Sender';
public priority = 1001;

constructor() {
this.processTelemetry = this._processTelemetry.bind(this);
}
public pause(): void {
this.isPauseInvoked = true;
}

public resume(): void {
this.isResumeInvoked = true;
}

public teardown(): void {
this.isTearDownInvoked = true;
}

flush(async?: boolean, callBack?: () => void): void {
this.isFlushInvoked = true;
if (callBack) {
callBack();
}
}

public processTelemetry(env: ITelemetryItem) { }

setNextPlugin(next: any) {
// no next setup
}

public initialize = (config: IConfiguration, core: AppInsightsCore, plugin: IPlugin[]) => {
}
it('Angular Plugin: component destroy triggers trackMetrics event', fakeAsync(() => {
init();
angularPluginTrackMetricSpy = spyOn(angularPlugin, 'trackMetric');
const channel = new ChannelPlugin();
const config: IConfiguration = {
instrumentationKey: 'instrumentation_key',
extensionConfig: {
[angularPlugin.identifier]: {
router
},
}
};

core.initialize(config, [angularPlugin, analyticsExtension, channel]);

private _processTelemetry(env: ITelemetryItem) {
}
}
// navigate to / - first time router navigates, home component is added
router.navigate(['/']);
tick(500);
// navigate to /search, home component is destroyed
router.navigate(['search']);
tick(500);
expect(angularPluginTrackMetricSpy).toHaveBeenCalledTimes(1);
expect(angularPluginTrackMetricSpy).toHaveBeenCalledWith({average: 0.5, name: 'Angular Component Existed Time (seconds)'}, {'Component Name': 'HomeComponent'});
// navigate to /home, search component is destroyed
router.navigate(['home']);
tick(500);
expect(angularPluginTrackMetricSpy).toHaveBeenCalledTimes(2);
expect(angularPluginTrackMetricSpy).toHaveBeenCalledWith({average: 0.5, name: 'Angular Component Existed Time (seconds)'}, {'Component Name': 'SearchComponent'});
}));
});
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,6 @@ const browserRollupConfigFactory = isProduction => {
commonjs({
include: 'node_modules/**'
}),
es3Poly(),
es3Check()
]
};

Expand Down Expand Up @@ -92,8 +90,6 @@ const nodeUmdRollupConfigFactory = (isProduction) => {
commonjs({
include: 'node_modules/**'
}),
es3Poly(),
es3Check()
]
};

Expand Down
Loading