In my latest project we embraced Application Insights as our logging and tracking platform. I am impressed by its capabilities and ease of use when hosting on Azure. It already has been very useful and it is free, because the amount of data we track is within 1 GB or 5M data points per month.
The only thing I felt was missing was (specific) user tracking. Out of the box AppInsights stores a user key with every tracked item, but this is a random value. This is good, because it lets you track and group all the telemetry of one user, but we don’t know who that user is. We wanted to add a username or email to the telemetry so we could track a specific user.
A good example, why tracking the user is useful, was a user who said there was a bug in the system. We couldn’t reproduce the issue, but by looking at his session we figured out he was using the system differently then we anticipated. It did spark a discussion if the system was clear enough, but it turned out not to be a bug. A good thing to know and it was very useful and a time saver that we could track the user.
Application Insights out of the box generates a random value because it doesn’t know about your users. You might be using Active directory, ASP.NET Identity, a custom solution or something else, so you have to link those up yourself.
Implement the ITelementryInitializer interface. The Initialize method is called on every telemetry item that is tracked. So it is important to keep the method very simple to not slow down your application. It will be called a lot. The easiest, and what we ended up doing, is set the CurrentPrincipal Identity Name as the AuthenticatedUserId. AuthenticatedUserId is a standard property available on every tracked item and in our system the Identity.Name is set to the users username (which is their email address). This is what the class looks like:
public class AppInsightsInitializer : ITelemetryInitializer
var appInsightsUserName = '@User.Identity.Name.Replace("\\", "\\\\")';
appInsightsUserName.replace(/[,;=| ]+/g, "_"));
More information can be found here: