10
votes

I am new to application insights and have set it up using no custom events and I'm using all the defaults. The application is build on MVC 5. In the ApplicationInsights.config there's a comment saying:

"When implementing custom user tracking in your application, remove this telemetry initializer to ensure that the number of users is accurately reported to Application Insights."

We have a page where you are required to login so the default user logging isn't saying that much and we would much rather have the username being the unique identifier. Based on the comment it seems like this should be some kind of common modification and therefor easy to modify. When trying to google on "custom user tracking" I do not find anything interesting which seems a bit odd...

So how do I link the user in Application Insights to my username instead of going on some cookie which seems to be the default behaviour?

1

1 Answers

14
votes

To link the user to your custom username, you can create the following telemetry initializer:

public class RealUserIDTelemetryInitializer:ITelemetryInitializer
{
    public void Initialize(Microsoft.ApplicationInsights.Channel.ITelemetry telemetry)
    {
        // Replace this with your custom logic
        if (DateTime.Now.Ticks % 2 > 0)
        {
            telemetry.Context.User.Id = "Ron Weasley";
        }
        else
        {
            telemetry.Context.User.Id = "Hermione Granger";
        }
    }
}

Then register this telemetry initializer in AI.config.

      <TelemetryInitializers>
 ....
        <Add Type="MyApp.RealUserIDTelemetryInitializer, MyApp" />
      </TelemetryInitializers>