Skip to content

Commit

Permalink
Add library
Browse files Browse the repository at this point in the history
  • Loading branch information
omaxel committed Mar 8, 2023
1 parent 5fd489a commit c615c57
Show file tree
Hide file tree
Showing 19 changed files with 2,424 additions and 434 deletions.
68 changes: 57 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,21 +1,67 @@
# AngularMsAppInsights
# Angular Microsoft Application Insights

<a alt="Nx logo" href="https://nx.dev" target="_blank" rel="noreferrer"><img src="https://raw.githubusercontent.com/nrwl/nx/master/images/nx-logo.png" width="45"></a>
Utility library to easily configure Microsoft Application Insights into an Angular project.

**This workspace has been generated by [Nx, a Smart, fast and extensible build system.](https://nx.dev)**
## Installation

## Development server
Install dependencies first:

Run `nx serve demo` for a dev server. Navigate to http://localhost:4200/. The app will automatically reload if you change any of the source files.
```
npm i @microsoft/applicationinsights-angularplugin-js @microsoft/applicationinsights-web
```

## Understand this workspace
then install the package:

Run `nx graph` to see a diagram of the dependencies of the projects.
```
npm i @omaxel/angular-ms-app-insights
```

## Remote caching
## Usage

Run `npx nx connect-to-nx-cloud` to enable [remote caching](https://nx.app) and make CI faster.
- Configure the module in `app.module.ts`

## Further help
```
AppInsightsModule.forRoot({
connectionString: 'YOUR_CONNECTION_STRING',~~~~
appName: 'YOUR_APP_NAME',
Visit the [Nx Documentation](https://nx.dev) to learn more.
// Optionals
appVersion: 'YOUR_APP_VERSION',
appBuildNumber: 'YOUR_APP_BUILD_NUMBER'
}),
```

- In the `app.component.ts` file, call the `init` method:

```
import { Component } from '@angular/core';
import { AppInsightsService } from "@omaxel/angular-ms-app-insights";
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
constructor(appInsightsService: AppInsightsService) {
appInsightsService.init();
}
}
```

## Track custom events

You can call the `trackEvent` method of `AppInsightsService` to track a custom event:

```
@Component({
selector: 'app-example',
templateUrl: './example.component.html'
})
export class ExampleComponent {
constructor(private appInsightsService: AppInsightsService) { }
onClick() {
this.appInsightsService.trackEvent('my-event-name', { myProperty: 'my-value' });
}
}
```
Empty file removed apps/.gitkeep
Empty file.
Empty file removed libs/.gitkeep
Empty file.
36 changes: 36 additions & 0 deletions libs/ms-app-insights/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"extends": ["../../.eslintrc.json"],
"ignorePatterns": ["!**/*"],
"overrides": [
{
"files": ["*.ts"],
"rules": {
"@angular-eslint/directive-selector": [
"error",
{
"type": "attribute",
"prefix": "angularMsAppInsights",
"style": "camelCase"
}
],
"@angular-eslint/component-selector": [
"error",
{
"type": "element",
"prefix": "angular-ms-app-insights",
"style": "kebab-case"
}
]
},
"extends": [
"plugin:@nrwl/nx/angular",
"plugin:@angular-eslint/template/process-inline-templates"
]
},
{
"files": ["*.html"],
"extends": ["plugin:@nrwl/nx/angular-template"],
"rules": {}
}
]
}
7 changes: 7 additions & 0 deletions libs/ms-app-insights/ng-package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"$schema": "../../node_modules/ng-packagr/ng-package.schema.json",
"dest": "../../dist/libs/ms-app-insights",
"lib": {
"entryFile": "src/index.ts"
}
}
17 changes: 17 additions & 0 deletions libs/ms-app-insights/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "@omaxel/angular-ms-app-insights",
"version": "1.0.2",
"author": "Omar Muscatello",
"repository": "github:omaxel/angular-ms-app-insights",
"peerDependencies": {
"@angular/core": ">=13",
"@angular/common": ">=13",
"@angular/router": ">=13",
"@microsoft/applicationinsights-angularplugin-js": "^3.0.0",
"@microsoft/applicationinsights-web": "^2.8.10"
},
"dependencies": {
"tslib": "^2.3.0"
},
"sideEffects": false
}
36 changes: 36 additions & 0 deletions libs/ms-app-insights/project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"name": "ms-app-insights",
"$schema": "../node_modules/nx/schemas/project-schema.json",
"projectType": "library",
"sourceRoot": "libs/ms-app-insights/src",
"prefix": "omx",
"targets": {
"build": {
"executor": "@nrwl/angular:package",
"outputs": ["{workspaceRoot}/dist/{projectRoot}"],
"options": {
"project": "libs/ms-app-insights/ng-package.json"
},
"configurations": {
"production": {
"tsConfig": "libs/ms-app-insights/tsconfig.lib.prod.json"
},
"development": {
"tsConfig": "libs/ms-app-insights/tsconfig.lib.json"
}
},
"defaultConfiguration": "production"
},
"lint": {
"executor": "@nrwl/linter:eslint",
"outputs": ["{options.outputFile}"],
"options": {
"lintFilePatterns": [
"libs/ms-app-insights/**/*.ts",
"libs/ms-app-insights/**/*.html"
]
}
}
},
"tags": []
}
3 changes: 3 additions & 0 deletions libs/ms-app-insights/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export * from './lib/app-insights.module';
export * from './lib/services/app-insights.service';
export * from './lib/models/app-insights-config.model';
30 changes: 30 additions & 0 deletions libs/ms-app-insights/src/lib/app-insights.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { ErrorHandler, ModuleWithProviders, NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AppInsightsConfigModel } from './models/app-insights-config.model';
import { APP_INSIGHTS_CONFIG } from './tokens/app-insights.token';
import { AppInsightsService } from './services/app-insights.service';
import { ApplicationinsightsAngularpluginErrorService } from '@microsoft/applicationinsights-angularplugin-js';

@NgModule({
imports: [CommonModule],
})
export class AppInsightsModule {
static forRoot(
config: AppInsightsConfigModel
): ModuleWithProviders<AppInsightsModule> {
return {
ngModule: AppInsightsModule,
providers: [
{
provide: APP_INSIGHTS_CONFIG,
useValue: config,
},
{
provide: ErrorHandler,
useClass: ApplicationinsightsAngularpluginErrorService,
},
AppInsightsService,
],
};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export interface AppInsightsConfigModel {
connectionString: string;

appName: string;
appVersion?: string;
appBuildNumber?: string;
}
75 changes: 75 additions & 0 deletions libs/ms-app-insights/src/lib/services/app-insights.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { Inject, Injectable } from '@angular/core';
import {
ApplicationInsights,
ICustomProperties,
IEventTelemetry,
} from '@microsoft/applicationinsights-web';
import { APP_INSIGHTS_CONFIG } from '../tokens/app-insights.token';
import { AppInsightsConfigModel } from '../models/app-insights-config.model';
import { Router } from '@angular/router';
import { AngularPlugin } from '@microsoft/applicationinsights-angularplugin-js';

@Injectable()
export class AppInsightsService {
appInsights?: ApplicationInsights;

constructor(
@Inject(APP_INSIGHTS_CONFIG)
private appInsightsConfig: AppInsightsConfigModel,
private router: Router
) {}

init() {
if (!this.appInsightsConfig?.connectionString) {
console.warn(`No Application Insights' connection string specified.`);
return;
}

const { connectionString, appName, appVersion, appBuildNumber } =
this.appInsightsConfig;

const angularPlugin = new AngularPlugin();

this.appInsights = new ApplicationInsights({
config: {
enableAutoRouteTracking: true,
connectionString: connectionString,
extensions: [angularPlugin],
extensionConfig: {
[angularPlugin.identifier]: { router: this.router },
},
},
});

this.appInsights.loadAppInsights();

this.appInsights.addTelemetryInitializer((telemetryItem) => {
telemetryItem.data ??= {};

telemetryItem.tags ??= [];
telemetryItem.tags['ai.cloud.role'] = appName;

telemetryItem.ver = appVersion || 'not-set';
telemetryItem.data['build'] = appBuildNumber || 'not-set';

if (window) {
telemetryItem.data['host'] = window.location.host;
telemetryItem.data['viewportHeight'] = window.innerHeight;
telemetryItem.data['viewportWidth'] = window.innerWidth;
telemetryItem.data['devicePixelRatio'] = window.devicePixelRatio;
telemetryItem.data['screenHeight'] = window.screen?.height;
telemetryItem.data['screenWidth'] = window.screen?.width;
}
});
}

trackEvent(eventName: string, customProperties: ICustomProperties) {
if (!this.appInsights) return;

const event: IEventTelemetry = {
name: eventName.toString(),
};

this.appInsights?.trackEvent(event, customProperties);
}
}
6 changes: 6 additions & 0 deletions libs/ms-app-insights/src/lib/tokens/app-insights.token.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { InjectionToken } from '@angular/core';
import { AppInsightsConfigModel } from '../models/app-insights-config.model';

export const APP_INSIGHTS_CONFIG = new InjectionToken<AppInsightsConfigModel>(
'app-insights-config'
);
26 changes: 26 additions & 0 deletions libs/ms-app-insights/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"compilerOptions": {
"target": "es2022",
"useDefineForClassFields": false,
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true
},
"files": [],
"include": [],
"references": [
{
"path": "./tsconfig.lib.json"
}
],
"extends": "../../tsconfig.base.json",
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true
}
}
12 changes: 12 additions & 0 deletions libs/ms-app-insights/tsconfig.lib.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../dist/out-tsc",
"declaration": true,
"declarationMap": true,
"inlineSources": true,
"types": []
},
"exclude": ["jest.config.ts", "src/**/*.test.ts", "src/**/*.spec.ts"],
"include": ["src/**/*.ts"]
}
9 changes: 9 additions & 0 deletions libs/ms-app-insights/tsconfig.lib.prod.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"extends": "./tsconfig.lib.json",
"compilerOptions": {
"declarationMap": false
},
"angularCompilerOptions": {
"compilationMode": "partial"
}
}
5 changes: 3 additions & 2 deletions nx.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"$schema": "./node_modules/nx/schemas/nx-schema.json",
"npmScope": "angular-ms-app-insights",
"affected": {
"defaultBase": "master"
"defaultBase": "main"
},
"tasksRunnerOptions": {
"default": {
Expand Down Expand Up @@ -56,5 +56,6 @@
"@nrwl/angular:component": {
"style": "scss"
}
}
},
"defaultProject": "ms-app-insights"
}
Loading

0 comments on commit c615c57

Please sign in to comment.