Reputation: 4325
(Added UPDATE 1 below which I think answers this question)
In a fairly simple ASP.NET Core 2 web app I have initialized in Program
like this:
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>()
.UseApplicationInsights()
.Build();
I haven't configured an instrumentation key in appSettings.json
yet because for now I'm running locally. When I run my app and force an exception on load of my home page I can see the exception logged in Visual Studio's telemetry search for Application Insights.
I now want to capture some details about the request in every logged event. I've followed some guidance and created an implementation of ITelemetryInitializer
:
public class CustomTelemetryInitializer : ITelemetryInitializer
{
private const string UserIdKey = "UserId";
private readonly IUserService _userService;
public CustomTelemetryInitializer(IUserService userService)
{
_userService = userService;
}
public void Initialize(ITelemetry telemetry)
{
if (!(telemetry is RequestTelemetry requestTelemetry)) return;
var props = requestTelemetry.Properties;
if (!props.ContainsKey(UserIdKey))
{
var user = _userService.GetCurrentUser();
if (user != null)
{
props.Add(UserIdKey, user.UserId);
}
}
}
}
This is largely following this guide. IUserService
is just a service which uses IHttpContextAccessor
to get the current ClaimsPrincipal
. You can see I'm trying to add the user's ID to the custom telemetry properties.
I've registered this ITelemetryInitializer
in Startup
like this:
services.AddSingleton<ITelemetryInitializer, CustomTelemetryInitializer>();
When I run my app again, I can see the debugger running through CustomTelemetryInitializer
and setting the property correctly. However, when I review the events logged in app insights, the custom property is not included. They look identical to the screenshot above.
I've tried moving the app insights initialization out of Program
and instead initializing it in Startup
after registering the ITelemetryInitializer
using services.AddApplicationInsightsTelemetry()
, but this makes no difference.
Anyone know what I'm doing wrong?
UPDATE 1
I've realised I made a mistake. My custom properties are being included for Request events after all. But not the Exception events. But I've now realised that these Exception events take a different implementation of ITelemetry
in Initialize
i.e. TraceTelemetry
. So I hadn't realised I was excluding these events from my custom properties.
Upvotes: 5
Views: 6810
Reputation: 3126
Glad you figured it out.
All ITelemetry
implementations in the SDK implements, ISupportProperties
which gives it Properties
collection. If you want to attach properties to every telemetry, you can cast to ISupportProperties
and set props.
Upvotes: 5