AndyMcKenna
AndyMcKenna

Reputation: 2647

Azure AppInsights default TelemetryInitializer - Javascript SDK

I'm using the NPM version of AppInsights and can't seem to get this telemetry initializer attached to every outgoing envelope:

import { ApplicationInsights } from '@microsoft/applicationinsights-web'
appInsights = new ApplicationInsights({ config: {
  instrumentationKey: 'removed',
  autoTrackPageVisitTime: true
}});

appInsights.loadAppInsights();

var userInitializer = (envelope) => {
  var telemetryItem = envelope.baseData;
  telemetryItem.properties = telemetryItem.properties || {};
  telemetryItem.properties["role"] = userProfile.role;
}
appInsights.queue.push(function () {
  appInsights.context.addTelemetryInitializer(userInitializer);
});

The problem is appInsights.queue is always undefined. The only thing I've been able to find is wrapping it in a check to make sure it doesn't try to execute twice but that's not the case here, it never executes. The telemetry initializer works fine if I call it individually before each tracking like this:

appInsights.addTelemetryInitializer(userInitializer);
appInsights.trackPageView();

When I console.log(appInsights) there definitely is never a queue property but it's used like this in every example.

Upvotes: 0

Views: 992

Answers (3)

Ahmad Hajou
Ahmad Hajou

Reputation: 1319

this worked for us

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

Upvotes: 3

Mark Wolff
Mark Wolff

Reputation: 124

You should be able to just do

appInsights.addTelemetryInitializer(userInitializer);

Upvotes: 0

Mohit Verma
Mohit Verma

Reputation: 5296

It happens when the code is invoked twice, and in the second time there is no "queue" anymore. The solution is to have the code snippet with a check

if (this.AppInsights.queue) {
        this.AppInsights.queue.push(function() { 
        this.AppInsights.context.addTelemetryInitializer(function(envelope) {
        var telemetryItem = envelope.data.baseData;

        telemetryItem.Properties = telemetryItem.Properties || {};
        telemetryItem.Properties["prop1"] = "This is a custom property";
        telemetryItem.Properties["prop2"] = "This is another custom property";
      });
    });
}

Hope it helps.

Upvotes: 0

Related Questions