gpt4 book ai didi

.net - 如何在 .NET 中关联请求/响应日志

转载 作者:行者123 更新时间:2023-12-03 02:12:31 24 4
gpt4 key购买 nike

非常常见的场景:

class MyServiceClient 
{
ILogger<MyServiceClient> _logger;

async Task Foo(Dto data)
{
_logger.LogDebug("Invoked API {ApiName}", new { ApiName = nameof(Foo), Data = data });

var requestContent = new StringContent(JsonSerializer.Serialize(data))

var httpResponse = await _httpClient.PostAsync(url, requestContent);

string responseStr = httpResponse.ReadAsStringAsync()
if (!httpResponse.IsSuccessStatusCode)
{
_logger.LogError("Failed API {ApiName}", new { ApiName = nameof(Foo), ResponseData = responseStr });
}

}
}
  1. 如何关联请求(“调用的 API”)和响应(“失败的 API”)日志?\并不是说我正在使用应用洞察记录器。
  2. 是否可以将依赖日志(http 客户端生成的日志)与此“操作”关联起来?

最佳答案

您可以使用 ILogger 实现来创建一个具有某些属性的 Scope,这些属性将附加到通过调用记录器生成的所有遥测数据:

using (_logger.BeginScope(new Dictionary<string, object>
{
{"CorrelationId", Guid.NewGuid()}
}))
{
_logger.LogWarning("Some Warning");
_logger.LogInformation("Some Info");
}

CorrelationId 将位于 Application Insights 中跟踪遥测的 customDimensions 字段中。

但是,如果您还想关联依赖项请求,您可以使用 TelemetryClient直接并显式地创建一个操作,该操作将用于关联该操作范围内所有生成的遥测数据:

using (var operation = _telemetryClient.StartOperation<DependencyTelemetry>("Foo"))
{
_logger.LogDebug("Invoked API {ApiName}", new { ApiName = nameof(Foo), Data = data });

var requestContent = new StringContent(JsonSerializer.Serialize(data))

var httpResponse = await _httpClient.PostAsync(url, requestContent);

string responseStr = httpResponse.ReadAsStringAsync()
if (!httpResponse.IsSuccessStatusCode)
{
_logger.LogError("Failed API {ApiName}", new { ApiName = nameof(Foo), ResponseData = responseStr });
}
}

您可以更进一步,设置遥测的属性来反射(reflect)调用是否成功:

...

if (!httpResponse.IsSuccessStatusCode)
{
_logger.LogError("Failed API {ApiName}", new { ApiName = nameof(Foo), ResponseData = responseStr });
operation.Telemetry.Success = false;
}

...

但请注意,如果您正在构建 .Net Web 应用程序,则可能已经有一个请求操作正在进行中,并且通过查找该请求遥测,您可能会发现跟踪遥测和依赖项已与该请求关联。

关于.net - 如何在 .NET 中关联请求/响应日志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72911852/

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