Home > Enterprise >  How to correlate related custom logs using ILogger and application insights?
How to correlate related custom logs using ILogger and application insights?

Time:10-13

I have a service, that performs some REST API calls and I do custom logging before and after the api call:

_logger.LogTrace("Invoked API {ApiName}", new { ApiName = apiName, Data = json });

var httpResponse = await _httpClient.PostAsync(url, new StringContent(json));
httpResponse.EnsureSuccessStatusCode();
var responseDto = await JsonSerializer.DeserializeAsync<ResponseDto>(httpResponse.Content.ReadAsStream())!;

if (!responseData.Success)
{
    _logger.LogWarning("Failed API {ApiName}", new { ApiName = apiName, Data = await httpResponse.Content.ReadAsStringAsync() });
}

The HttpClient also produces logs.

What is the recommended approach for correlating the logs, so that I can easily find related logs in application insights portal?

I would like all logs produced by HttpClient or possibly ADO.NET etc to be related to my custom log.

CodePudding user response:

The ILogger logs are automatically correlated, if you enable the entire ApplicationInsights for Asp.Net Core following this doc: https://learn.microsoft.com/en-us/azure/azure-monitor/app/asp-net-core For example, all logs will have same operationId, if they are done as part of the same request.

Also check: https://learn.microsoft.com/en-us/azure/azure-monitor/app/correlation

CodePudding user response:

If you want to just add your own correlation ID, then you can do so using logger data scopes:

using (logger.BeginScope(new Dictionary<string, object>{
    ["OperationId"] = Guid.NewGuid().ToString("N"),
}))
{
  ... // logs from any code in here will have an OperationId
}
  • Related