How to add global metadata to ASP.NET Core logging?

869 Views Asked by At

I'd like to add my app's build number to all logs in an ASP.NET Core 3.1 app that is using Application Insights for log storage. Is this possible without having to use BeginScope and EndScope everywhere? I assumed it would be part of the ConfigureLogging startup hook, but didn't see anything. I've done this in the past with Serilog's enrichers, but am not using that library currently.

1

There are 1 best solutions below

0
On BEST ANSWER

You can achieve that with TelemetryInitializer. (https://learn.microsoft.com/en-us/azure/azure-monitor/app/api-filtering-sampling#addmodify-properties-itelemetryinitializer)

public class BuildNumberTelemetryInitializer : ITelemetryInitializer
  {
    public void Initialize(ITelemetry telemetry)
    {
        (telemetry as ISupportProperties).Properties.Add("BuildNumber", "ValueForBuildNumber"); 
    }

You need to add this initializer to the config, which is done like below if you are on Asp.Net Core applications.

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<ITelemetryInitializer, BuildNumberTelemetryInitializer >();
}