.net core ILogger application insight with custom properties

362 views Asked by At

I would like to add custom property to application insight which is coming in applicaion header. Is there a way to do without making much changes in existing code?

I have configured the loggin in my .net core application as below.

`services.AddLogging(options => { options.AddFilter("", _logLevel);

            // pass the InstrumentationKey provided under the appsettings
            options.AddApplicationInsights(Configuration["AppInsightInstrumentKey"]);
        });`

And to write the logs I have called the function as private readonly ILogger<MyController> _logger; _logger.LogError(ex.ToString());

I would like to add custom property to application insight which is coming in applicaion header. Is there a way to do without making much changes in existing code?

i would like to use same method _logger.LogError and it should add customer properties as well.

1

There are 1 answers

8
Sampath On
  • Using ITelemetryInitializer, it is possible to add additional properties to an existing request and git reference ApplicationInsightsRole with package Microsoft.Extensions.Logging.ApplicationInsights.

enter image description here

   _logger = new TelemetryClient(configuration);

       
        Person user = new Person() { FirstName = "Cat", LastName = "Lady" };

    
        Dictionary<string, string> customProperties = new Dictionary<string, string>()
        {
            { "FirstName", user.FirstName },
            { "LastName", user.LastName }
        };

        TrackTrace("User details", SeverityLevel.Information, customProperties);

        telemetryClient.TrackTrace("User details", SeverityLevel.Information, customProperties);

For Exception:

 _logger.TrackException(telemetry);

enter image description here

enter image description here

  • More details with Custom properties for each request in Application Insights metrics SO and logging