Adding custom properties for each request in Application Insights metrics

JYL picture JYL · Mar 13, 2015 · Viewed 25.5k times · Source

I d'like to add custom properties to metrics taken by Application Insights to each request of my app. For example, I want to add the user login and the tenant code, such as I can segment/group the metrics in the Azure portal.

The relevant doc page seems to be this one : Set default property values

But the example is for an event (i.e. gameTelemetry.TrackEvent("WinGame");), not for an HTTP request :

var context = new TelemetryContext();
context.Properties["Game"] = currentGame.Name;
var gameTelemetry = new TelemetryClient(context);
gameTelemetry.TrackEvent("WinGame");

My questions :

  1. What is the relevant code for a request, as I have no specific code at this time (it seems to be automatically managed by the App Insights SDK) : Is just creating a TelemetryContext sufficient ? Should I create also a TelemetryClient and if so, should I link it to the current request ? How ?
  2. Where should I put this code ? Is it ok in the Application_BeginRequest method of global.asax ?

Answer

Jitendra Patil picture Jitendra Patil · Oct 4, 2016

It looks like adding new properties to existing request is possible using ITelemetryInitializer as mentioned here.

I created sample class as given below and added new property called "LoggedInUser" to request telemetry.

public class CustomTelemetry : ITelemetryInitializer
{
    public void Initialize(ITelemetry telemetry)
    {
        var requestTelemetry = telemetry as RequestTelemetry;
        if (requestTelemetry == null) return;
        requestTelemetry.Properties.Add("LoggedInUserName", "DummyUser");

    }
}

Register this class at application start event. Example below is carved out of sample MVC application I created

 public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

        TelemetryConfiguration.Active.TelemetryInitializers
    .Add(new CustomTelemetry());
    }
}

Now you can see custom property "LoggedInUserName" is displayed under Custom group of request properties. (please refer screen grab below)

Appinsight with custom property