簡體   English   中英

如何在 .NET 中關聯請求/響應日志

[英]How to associate request/response logs in .NET

很常見的場景:

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

您可以更進一步,設置遙測屬性以反映調用是否成功:

...

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

...

但請注意,如果您正在構建一個 .Net Web 應用程序,可能已經有一個請求操作正在進行中,並且通過查找該請求遙測數據,您可能會發現跟蹤遙測數據和依賴項已經與該請求相關聯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM