Setting username in application insights

纵饮孤独 提交于 2019-11-29 09:11:11

问题


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:


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>


来源:https://stackoverflow.com/questions/30434924/setting-username-in-application-insights

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!