Sitecore - Application Insights Telemetry - Custom properties

320 Views Asked by At

I am struggling with accomplishing the following scenario: I need to create a custom property for Application Insights, containing an identifier for the user (which is read from the data store at login time).

Went through several articles on the matter, but it does not seem to work.

I tried the following so far:

  1. Implemented a custom telemetry initializer and loaded it in a Sitecore pipeline. The problem here is that I can't access the session object, as it's always NULL. After some research I realized that it is triggered before the session is even created, so then I went to the second option.
  2. Tried to load the telemetry initializer in a HttpRequestProcessor, I was able to access the session, but the Initialize method is never triggered afterwards. Can't say I understand what is happening.I added the initializer as follows TelemetryConfiguration.Active.TelemetryInitializers.Add(new UserIdTelemetryInitializer([injected_service])), in the constructor of the processor, so it is only triggered once.

Does anyone have any thoughts on what exactly I am doing wrong? If you have a code example that works for you in a similar case, I would be grateful.

Let me know if you need additional information (might have been too brief about it).

1

There are 1 best solutions below

0
LarryX On

ASP.NET MVC you need to run this once on startup or Global.asax

Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.Active.TelemetryInitializers.Add(new UserIdTelemetryInitializer());

The implementation of UserIdTelemetryInitializer:

public class UserIdTelemetryInitializer : ITelemetryInitializer
{
    public void Initialize(Microsoft.ApplicationInsights.Channel.ITelemetry telemetry)
    {
        {
            if (HttpContext.Current?.Session == null)
                return;

            if (HttpContext.Current.Session["UserId"] == null)
            {
                HttpContext.Current.Session["UserId"] = Guid.NewGuid().ToString();
            }

            telemetry.Context.User.Id = (string)HttpContext.Current.Session["UserId"];
            telemetry.Context.Session.Id = HttpContext.Current.Session.SessionID;

            var authUser = _sessionManager.GetAuthenticatedUser<UserDetails>();
            if (authUser != null)
            {
                telemetry.Context.User.AuthenticatedUserId = authUser.UserId;
            }
        }

    }
}