Reputation: 2899
I am looking to add a logged-in user's name to Application Insights to replace the cookie by default. I found this post that does something like this
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";
}
}
}
My question, is how do I pass data into this? I have a login method on my Api that returns some info, but calling into this Initializer is something I am confused on.
Upvotes: 2
Views: 862
Reputation: 29711
We once had that same issue, although not for a user id but for an operation id. But the same principle can be applied here. We used a Func<T>
that provides the data for the initializer (See full code of the initializerhere and the usage here).
public class RealUserIDTelemetryInitializer:ITelemetryInitializer
{
private readonly Func<string> usernameProvider;
public RealUserIDTelemetryInitializer(Func<string> usernameProvider)
{
this.usernameProvider = usernameProvider;
}
public void Initialize(Microsoft.ApplicationInsights.Channel.ITelemetry telemetry)
{
telemetry.Context.User.Id = usernameProvider.Invoke();
}
}
Then add the initializer using code:
configuration.TelemetryInitializers.Add(new RealUserIDTelemetryInitializer(() =>
CallContext.LogicalGetData(UserId)?.ToString()));
As you can see in our case the data was provided using data on the current thread but in your case I suppose there is easier access to the username so you wil probably inject another Func.
Upvotes: 1