Modifying and Filtering Telemetry with AppInsights JavaScript SDK Telemetry Initializer

Telemetry Initializers and, more recently, Telemetry Processors, is now quite well known and used for .NET SDK. However from the forum questions we are discovering, that not as many customers are aware, that AppInsights JavaScript SDK also supports simple, but very powerful Telemetry Initializer concept, which allows to modify and filter your data.

This is API reference for telemetry initializer for AppInsights JavaScript SDK.

And here's a simple example. Suppose you would like to strip URL from reported page views. Here's how you would do it. Insert this code immediately before the last line of the snippet

 window.appInsights = appInsights; 
 // Add telemetry initializer
appInsights.queue.push(function () { 
appInsights.context.addTelemetryInitializer(function (envelope) { 
if (envelope.name === Microsoft.ApplicationInsights.Telemetry.PageView.envelopeType)  { 
   envelope.data.baseData.url = "[stripped_url]"; 
  } 
 }); 
 }); 
 // end of insertion
appInsights.trackPageView(); 

 

Another example. Suppose you would like to initialize operation ID or operation Name based on your internal logic to enable correlation working in the way specific to your application. Here's how would do it:

 window.appInsights = appInsights; 
 // Add telemetry initializer
appInsights.queue.push(function () { 
appInsights.context.addTelemetryInitializer(function (envelope) { 
envelope.tags["ai.operation.id"] = "my-op-id"; 
envelope.tags["ai.operation.name"] = "my-op-name"; 
  }); 
 }); 
 // end of insertion
appInsights.trackPageView(); 

To explore the properties that you can change I suggest creating an initializer and then putting a breakpoint in your browser tools to see what properties are present on the tags object and properties that are present on the telemetry item for a particular telemetry type.

Filtering data

To use telemetry initializer in JavaScript SDK for filtering, simply return false from the function. For example, here's how I can disable all Client Performance events

 window.appInsights = appInsights; 
 // Add telemetry initializer
appInsights.queue.push(function () { 
appInsights.context.addTelemetryInitializer(function (envelope) { 
if (envelope.name === Microsoft.ApplicationInsights.Telemetry.PageViewPerformance.envelopeType)  { 
   return false; 
  } 
 }); 
 }); 
 // end of insertion
appInsights.trackPageView(); 

 

You can also add your data by calling appInsights.trackX from inside the initializer, however obviously you need to be careful with potential stack overflow.
Do you have other examples of how you're using telemetry initializers for AppInsights JavaScript SDK? Please share your feedback!