如何使用ILogger和应用程序见解关联相关的自定义日志



我有一个服务,它执行一些REST API调用,并在API调用前后进行自定义日志记录:

_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() });
}

HttpClient还会生成日志。

建议使用什么方法关联日志,以便我可以在应用程序洞察门户中轻松找到相关日志?

我希望HttpClient或ADO.NET等生成的所有日志都与我的自定义日志相关。

编辑:我知道ASP.NET Core MVC或Pages会根据请求使用OperationTelemetry自动关联日志。我需要同样的其他场景:控制台应用程序、富客户端、blazor服务器(使用websockets代替请求(

因此,只有当遥测是操作的一部分时,它才会自动链接。例如,当控制器接收到请求时,就会创建一个操作。这是由运行时完成的。

如果没有挂起的操作,则需要手动添加上下文,以便关联遥测,或者创建自己的操作,将遥测与特定操作关联起来。你可以这样做:

using (var op = _telemetryClient.StartOperation<DependencyTelemetry>($"Invoke API {ApiName}"))
{
_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)
{
op.Telemetry.Success = false;
_logger.LogWarning("Failed API {ApiName}", new { ApiName = apiName, Data = await httpResponse.Content.ReadAsStringAsync() });
}
}

现在,所有遥测将在操作范围内进行关联。

如果您按照此文档为Asp.Net Core启用整个ApplicationInsights,则ILogger日志将自动关联:https://learn.microsoft.com/en-us/azure/azure-monitor/app/asp-net-core例如,如果所有日志都是作为同一请求的一部分完成的,那么它们将具有相同的operationId。

同时检查:https://learn.microsoft.com/en-us/azure/azure-monitor/app/correlation

如果您只想添加自己的相关性ID,那么您可以使用记录器数据范围:

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

最新更新