Azure fails to consistently retain TrackEvent data from Application Insights

Our team is currently in the process of integrating the Node SDK to track custom events within our codebase. The service we've developed is invoked from an asynchronous method chain and is executed in Azure Functions:

public async handleEvent(event: Event) {
    // Perform operations

    // Send event report
    this.reportEvent(event);
}

private reportEvent(event: Event) {
    if (this._applicationInsightsService) {
        this._applicationInsightsService.reportEvent(event)
        this._context.log("Successfully sent event to application insights")
    } else {
        this._context.log("Could not send metrics to application insights, service is not defined")
    }
}

The structure of the service itself is as follows:

export class ApplicationInsightsService {

    private _instance: ApplicationInsights

    private constructor(connectionString: string) {
        this._instance = new ApplicationInsights({ 
            config: {
                connectionString: connectionString
            } 
        })
        this._instance.loadAppInsights()
    }

    public static create() {
        if (process.env.APPLICATION_INSIGHTS_CONNECTION_STRING === undefined) {
            throw new Error("APPLICATION_INSIGHTS_CONNECTION_STRING undefined, cannot report metrics")
        }
        return new ApplicationInsightsService(process.env.APPLICATION_INSIGHTS_CONNECTION_STRING)
    }

    public reportEvent(event: Event) {
        this._instance.trackEvent({
            name: event.type,
            properties: event
        })
        this._instance.flush()
    }
}

Despite implementing the code, the events I transmit do not appear in the Azure Portal when I check the customEvents table. I have waited for over 10 minutes knowing that there may be delays with application insights.

I attempted to make the flush call asynchronous and utilize await, but this did not resolve the issue either:

Promise.resolve(this._instance.flush(true))

The environment variable

APPLICATION_INSIGHTS_CONNECTION_STRING
adheres to the format
InstrumentationKey=xxx;IngestionEndpoint=https://westeurope-1.in.applicationinsights.azure.com/
.

The problem mirrors a scenario discussed in C# Application Insight Failure: TrackEvent Does not send to Azure Application Insight. Do I truly need to account for timing by incorporating sleep or timeouts?

Upon running the code, the log does not indicate any errors or anomalies:

[12/17/2020 11:06:10 AM] Executing 'Functions.EventHandler' (Reason='New ServiceBus message detected on 'integrator-events'.', Id=812ccf8f-3cd3-4c75-8ab4-20614556d597)
[12/17/2020 11:06:10 AM] Trigger Details: MessageId: 125f60d79c5a4b029a417bee68df95d7, DeliveryCount: 1, EnqueuedTime: 12/17/2020 11:06:11 AM, LockedUntil: 12/17/2020 11:07:11 AM, SessionId: (null)
[12/17/2020 11:06:10 AM] Received event
[12/17/2020 11:06:10 AM] Successfully sent event to application insights
[12/17/2020 11:06:10 AM] Executed 'Functions.EventHandler' (Succeeded, Id=812ccf8f-3cd3-4c75-8ab4-20614556d597)

What could be the missing link here?

Update

Acknowledging the existence of both a JavaScript and a Node SDK adds another layer of complexity. While I will experiment with the Node SDK, I fail to see why the former should not function properly.

Solution

The revised implementation of the ApplicationInsightsService appears as below:

// Previously:
// import { ApplicationInsights } from "@microsoft/applicationinsights-web"
import { TelemetryClient } from "applicationinsights"

export class ApplicationInsightsService {

    private _instance: TelemetryClient

    private constructor(connectionString: string) {
        this._instance = new TelemetryClient(connectionString)
    }
}

For node applications:

Do:

npm install --save applicationinsights

Don't:

npm install --save @microsoft/applicationinsights-web

Answer №1

The ApplicationInsightsService can be implemented as shown below:

// Previous implementation:
// import { ApplicationInsights } from "@microsoft/applicationinsights-web"
import { TelemetryClient } from "applicationinsights"

export class ApplicationInsightsService {

    private _instance: TelemetryClient

    private constructor(connectionString: string) {
        this._instance = new TelemetryClient(connectionString)
    }
}

If using node applications:

Recommended:

npm install --save applicationinsights

Avoid:

npm install --save @microsoft/applicationinsights-web

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

When configuring the Redux logger, the type 'Middleware<{}, any, Dispatch<UnknownAction>>' is not compatible with type 'Middleware<{}, any, Dispatch<AnyAction>>'

In my React project, I have defined the redux logger with the package version "redux-logger": "^3.0.6" in the file store.ts as shown below: import { configureStore } from '@reduxjs/toolkit'; import rootReducer from '@/re ...

Leveraging generics within TypeScript

I have developed a class in TypeScript that uses generics. export class ModelTransformer { static hostelTransformer: HostelTransformer; static fromAtoB(instance: T): U { if (instance instanceof HostelType) { return ModelTrans ...

Exploring the benefits of leveraging TypeScript with AWS NodeJS for improved stacktrace visibility over traditional JavaScript

I'm contemplating the idea of transitioning my existing JavaScript codebase to incorporate TypeScript in NodeJS. One aspect that I am concerned about is being able to view the stack trace in AWS CloudWatch (request log) in case an error occurs during ...

Automatically identify the appropriate data type using a type hint mechanism

Can data be interpreted differently based on a 'type-field'? I am currently loading data from the same file with known type definitions. The current approach displays all fields, but I would like to automatically determine which type is applicab ...

Is there a way to enable autofill functionality if an email already exists in the database or API within Angular 12?

In order to auto-fill all required input fields if the email already exists in the database, I am looking for a way to implement this feature using API in Angular. Any guidance or suggestions on how to achieve this would be greatly appreciated. ...

How to upload files from various input fields using Angular 7

Currently, I am working with Angular 7 and typescript and have a question regarding file uploads from multiple input fields in HTML. Here is an example of what I am trying to achieve: <input type="file" (change)="handleFileInput($event.target.files)"&g ...

Can dynamic string types be declared in Typescript?

Let's consider the following scenario: export enum EEnv { devint, qa1 }; export type TEnv = keyof typeof EEnv; export const env:Record<TEnv, {something:number}> = { devint: { something: 1, }, qa1: { something: 1, }, } Now, I ai ...

Angular: A Guide to Displaying HTML Content from a TypeScript File

I implemented jQuery dataTable to showcase data on a list view. In my attempt to populate data into the dataTable, I used the following approach. Within users.component.ts: getUsers() { this.UserService.getUsersList() .subscribe( succ ...

Is there a method or alternative solution for deconstructing TypeScript types/interfaces?

Imagine a scenario where a class has multiple type parameters: class BaseClass<T extends T1, U extends U1, V extends V1, /* etc. */ > Is there a method to consolidate these type arguments in a way that allows for "spreading" or "destructuring," sim ...

Angular example of Typeahead feature is sending a blank parameter to the backend server

I am currently trying to implement a similar functionality to the example provided at this link in my Angular frontend application. The goal is to send a GET request to my backend with the search parameter obtained from an input field. However, even thoug ...

Removing multiple items from a list in Vue JS using splice function

I have a problem with my app's delete feature. It successfully deletes items from the database, but there seems to be an issue in the front-end where I can't remove the correct items from the list. Check out this demo: https://i.sstatic.net/eA1h ...

Implementing the strictNullCheck flag with msbuild

Can strict null checks be enabled when compiling using msbuild? I see in the documentation that the compiler option is --strictNullChecks, but I couldn't find any specific entry for it on the msbuild config page. Is there a method to activate this f ...

Which data structure is suitable for storing a JSON object?

Currently, I have a form set up in the following way: using (Ajax.BeginRouteForm( ... new AjaxOptions { HttpMethod = "POST", OnFailure = "OnFailure", OnSuccess ...

Unable to successfully import Node, JS, or Electron library into Angular Typescript module despite numerous attempts

I'm still getting the hang of using stack overflow, so please forgive me if my question isn't formulated correctly. I've been doing a lot of research on both stack overflow and Google, but I can't seem to figure out how to import Electr ...

Instructions for adding a method to a prototype of a generic class in TypeScript

My current challenge involves adding a method to a prototype of PromiseLike<T>. Adding a method to the prototype of String was straightforward: declare global { interface String { handle(): void; } } String.prototype.handle = functi ...

The 'SVGResize' or 'onresize' property is not available on the 'SVGProps<SVGSVGElement>' type

Using React with SVG I'm facing an issue with handling the resizing event of an svg element. I have looked into using the SVGResize and onresize events, but encountered compilation errors when trying to implement them: const msg1 = (e: any) => co ...

A method for comparing two arrays containing identical objects and then storing the results in a variable

I have an item stored within two other items called formKeyValues and form formKeyValues https://i.stack.imgur.com/nRfiu.png form https://i.stack.imgur.com/eDpid.png I am looking to extract only the keys and values from formKeyValues and place them in ...

Tips for managing Signal inputs with the updated control flow for conditional rendering in Angular version 17.2

I'm having trouble navigating the control flow and a Signal Input in Angular 17.2. In one of my components, I have this input: index = input<number|null>(); The template for this component needs to account for the fact that index can also be 0 ...

Exploring .ENV Variables using Angular 2 Typescript and NodeJS

After completing the Angular2 Quickstart and tutorials, I'm now venturing into connecting to a live REST Api. I need to include authentication parameters in my Api call, and from what I've gathered, it's best practice to store these paramete ...

Function that observes with the pipe syntax

Is it possible to apply map, switchMap, or any other operator in conjunction with a function that outputs an observable? The objective here is to transform the result of the observable function and utilize that value during the subscription to another ob ...