Adding custom properties for each request in Application Insights metrics

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


Related to the first question "how to add custom event to my request / what is the relevant code to a request", I think the main confusion here is related to the naming.

The first thing that we need to point out is that there are different kinds of information that we can capture with Application Insights:

  1. Custom Event
  2. Request
  3. Exception
  4. Trace
  5. Page View
  6. Dependency

Once we know this, we can say that TrackEvent is related to "Custom Events", as TrackRequest is related to Requests.

When we want to save a request, what we need to do is the following:

 var request = new RequestTelemetry();
 var client = new TelemetryClient();
 request.Name = "My Request";
 client.TrackRequest(request);

So let's imagine that your user login and tenant code both are strings. We could make a new request just to log this information using the following code:

public void LogUserNameAndTenant(string userName, string tenantCode)
{
    var request = new RequestTelemetry();

    request.Name = "My Request";
    request.Context.Properties["User Name"] = userName;
    request.Context.Properties["Tenant Code"] = tenantCode;

    var client = new TelemetryClient();
    client.TrackRequest(request);
}

Doing just a TelemetryContext will not be enough, because we need a way to send the information, and that's where the TelemetryClient gets in place.

I hope it helps.