Adding a custom role in Angular TypeScript in Microsoft AppInsights is a straightforward process that can provide valuable

I have an angular project where I am looking to incorporate AppInsight with custom telemetry (role). The project is built in Angular using TypeScript, and I successfully integrated appinsights by following this tutorial. However, when attempting to add custom telemetry as outlined in this guide, which is primarily for Java/JavaScript/Node.JS, I encountered an issue.

When trying to implement the JS code snippet below:

this.appInsights.queue.push(() => {
      this.appInsights.addTelemetryInitializer((envelope) => {
        envelope.tags["ai.cloud.role"] = "your role name";
        envelope.tags["ai.cloud.roleInstance"] = "your role instance";
      });
    });

An error was thrown:

TS2339: Property 'queue' does not exist on type 'Initialization'. 

This could be due to the code being in JavaScript rather than TypeScript.

I also attempted a different approach from this source, but it did not yield any successful results:

this.appInsights.addTelemetryInitializer(envelope => {
  envelope.tags['ai.cloud.role'] = 'your cloud role name';
  envelope.baseData.properties['item'] = 'some property';
});

The provided code belongs to my MonitoringService:

import {Injectable} from '@angular/core';
import {environment} from '../../../../environments/environment';
import {ApplicationInsights} from '@microsoft/applicationinsights-web';

@Injectable()
export class MonitoringService {
  appInsights: ApplicationInsights;

  constructor() {
    this.appInsights = new ApplicationInsights({
      config: {
        instrumentationKey: environment.appInsights.instrumentationKey,
        enableAutoRouteTracking: true // option to log all route changes
      }
    });
    this.appInsights.queue.push(() => {
      this.appInsights.addTelemetryInitializer((envelope) => {
        envelope.tags["ai.cloud.role"] = "your role name";
        envelope.tags["ai.cloud.roleInstance"] = "your role instance";
      });
    });
    this.appInsights.loadAppInsights();
  }

  logPageView(name?: string, url?: string) { // option to call manually
    this.appInsights.trackPageView({
      name: name,
      uri: url
    });
  }

  logEvent(name: string, properties?: { [key: string]: any }) {
    this.appInsights.trackEvent({name: name}, properties);
  }

  logMetric(name: string, average: number, properties?: { [key: string]: any }) {
    this.appInsights.trackMetric({name: name, average: average}, properties);
  }

  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);
  }
}

I even tried updating the Microsoft dependency from version 2.4.4 to 2.5.10, yet it did not produce any noticeable changes.

Despite having a role configured within AppInsights, it seems that it is not being set correctly.

https://i.sstatic.net/gQhBV.png

Answer №1

Although my issue was not identical, I found that running the telemetry initializer after loadAppInsights resolved it for me:

      this.appInsights.loadAppInsights();

      const telemetryInitializer = (envelope) => {
        envelope.tags['ai.cloud.role'] = 'your-app-name';
      };
      this.appInsights.addTelemetryInitializer(telemetryInitializer);

(source: https://github.com/microsoft/applicationinsights-js#example-setting-cloud-role-name)

Have you tried this approach?

(Running version 2.5.9)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can you choose to declare a type in TypeScript, or is it required for every variable

Has anyone encountered a problem similar to this? type B = a ? 'apple' | 'grape' | 'orange' : 'apple' | 'grape'; // This code results in an ERROR! const x = (a: boolean, b: B) => console.log('foo&a ...

Invoke the built-in matcher within a Playwright custom matcher

I am in the process of implementing a custom matcher for Playwright based on the information provided in the official documentation on extending expect. In a similar vein to this unanswered discussion, my goal is to invoke an existing matcher after modifyi ...

Encountering unproductive errors with custom editor extension in VS Code

I'm currently developing a custom vscode extension for a read-only editor. During testing, I encountered a rather unhelpful error message. Can anyone offer some insight on what might be causing this issue? 2022-11-25 11:36:17.198 [error] Activating ex ...

The SideNav SpyOn feature failed to locate the specified method

In the test project I am working on, there is a side navigation menu. I need to create a simple test to verify that when I click the button, the sidenav opens or closes. The AppComponent interacts with the sidebar through its dependency, sidenavbar. it(&a ...

Confirm the existence of duplicates within an Angular reactive form

I am working with a reactive form that looks like this: https://stackblitz.com/edit/angular-form-array-example After clicking the "add credentials" button 3 times, I have 3 sets of elements for username and password. In the first row, I enter the usernam ...

Can you provide guidance on how to communicate an event between a service and a component in Angular 2?

I'm currently working with angular2-modal to create a modal alert in my application. I am specifically trying to capture the confirm event that occurs when the modal is triggered. Does anyone know how I can achieve this? ...

What strategies can I use to address the issue of requiring a type before it has been defined?

Encountered an intriguing challenge. Here are the types I'm working with: export interface QuestionPrimative { question : string; id : string; name : string; formctrl? : string; formgrp? : string; lowEx ...

The 'import.meta' meta-property can only be used with the '--module' set to 'es2020', 'esnext', or 'system'.ts(1343)

Whenever I attempt to utilize import.meta.url (as demonstrated in the Parcel docs), I am consistently met with the error message "The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es ...

Is there an easier method to utilize ES6's property shorthand when passing an object in TypeScript, without needing to prefix arguments with interface names?

When working with JavaScript, I often find myself writing functions like the one below to utilize ES6's property shorthand feature: function exampleFunction({param1, param2}) { console.log(param1 + " " + param2); } //Usage: const param1 = "param1" ...

Validating React components with TypeScript using an array structure where the field name serves as the key

Trying to implement form validation with React. I have a main Controller that contains the model and manages the validation process. The model is passed down to child controllers along with the validation errors. I am looking for a way to create an array ...

The File plugin in Ionic 3 is encountering difficulties in writing files on the device

I am developing an app using Ionic 3 and the file plugin. My goal is to write a JSON string to a JSON file located in my assets folder with the following hierarchy: assets -> mock -> msg-list.json , with "assets" as the main folder in the Ionic file ...

Intercepting HTTP requests on specific routes with Angular 4+ using an HTTP Interceptor

I've developed an HTTP_INTERCEPTOR that needs to function on certain routes while excluding others. Initially, it was included in the main app module file. However, after removing it from there and adding it to specific modules, the interceptor conti ...

It is impossible for me to invoke a method within a function

I am new to working with typescript and I have encountered an issue while trying to call the drawMarker() method from locateMe(). The problem seems to be arising because I am calling drawMarker from inside the .on('locationfound', function(e: any ...

Using BehaviorSubject.next does not automatically refresh the view when using the async pipe

I am having trouble updating my Angular view with Google Places using the Google Places Js API and BehaviorSubject.next. The asynchronous pipe doesn't always reflect the updates immediately. Sometimes, it takes about 15 seconds for the view to update ...

Launching an Angular 2 application on PCF

I am encountering an issue while attempting to deploy my angular2 application on pivotal cloud foundry. I diligently followed the instructions provided here, but despite no errors being present in the developer console, I continuously encounter the message ...

Maximize the benefits of using React with Typescript by utilizing assignable type for RefObject

I am currently working with React, Typescript, and Material UI. My goal is to pass a ref as a prop. Within WidgetDialog, I have the following: export interface WidgetDialogProps { .... ref?: React.RefObject<HTMLDivElement>; } .... <div d ...

Issues with showing data in Angular Material tables

I recently deployed my Angular Application on a server and encountered an issue with the Angular Material table. Despite data being present in the logs, it does not display on the table. This problem only occurs in production, as everything works perfectl ...

angular2 fullCalendar height based on parent element

Currently, I am using angular2-fullcalendar and encountering an issue with setting the height to 'parent'. The parent element is a div but unfortunately, it does not work as expected. The navigation bar appears fine, however, the calendar itself ...

Exploring TypeScript's Classes and Generics

class Person { constructor(public name: string) {} } class Manager extends Person {} class Admin extends Person {} class School { constructor(public name: string) {} } function doOperation<T extends Person>(person: T): T { return person; } ...

When using translate.get with an array of strings in Angular 5, the function will return both the keys and values, not just

Currently, I am utilizing Angular 5 to manage internationalization through ngx-translate within my code. To elaborate on the issue at hand, I have a data table that pulls information from a web service and displays it correctly. There is also a button tha ...