gpt4 book ai didi

.net - 如何使用 ILogger 和应用程序洞察关联相关的自定义日志?

转载 作者:行者123 更新时间:2023-12-02 23:54:34 28 4
gpt4 key购买 nike

我有一个服务,它执行一些 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 而不是请求)

最佳答案

因此,遥测仅在属于操作的一部分时才会自动链接。例如,当 Controller 收到请求时,就会创建一个操作。这是由运行时完成的。

如果您没有待处理的操作,则需要手动添加上下文,以便可以关联遥测数据,或者可以创建自己的操作以将遥测数据与该特定操作相关联。您可以这样做:

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

现在所有遥测数据都将在操作范围内关联。

关于.net - 如何使用 ILogger 和应用程序洞察关联相关的自定义日志?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74042775/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com