How to add custom dimension to Application Insights traces from .NET Core? Any pointers are welcome.
If it's a .net core web project, you can use ITelemetryInitializer to add custom dimension.
First, add a new class named MyTelemetryInitializer
to the project:
public class MyTelemetryInitializer: ITelemetryInitializer
{
public MyTelemetryInitializer()
{
}
public void Initialize(ITelemetry telemetry)
{
if (telemetry is TraceTelemetry traceTelemetry)
{
if (!traceTelemetry.Properties.ContainsKey("my_custom_1"))
{
//add the custom dimension here
traceTelemetry.Properties["my_custom_1"] = "test 12346";
}
}
}
}
Then in the Startup.cs -> ConfigureServices method, add these lines of code:
services.AddApplicationInsightsTelemetry();
services.AddSingleton<ITelemetryInitializer, MyTelemetryInitializer>();
And for testing purpose, in the HomeController, I have this Index method to send trace message:
public IActionResult Index()
{
TelemetryClient client = new TelemetryClient();
client.TrackTrace("it is a trace message from index page");
return View();
}
At last, run the project. Then nav to azure portal -> application insights, you can see the custom dimension is added.