diff --git a/src/ReC.Client/ReCClientHelpers.cs b/src/ReC.Client/ReCClientHelpers.cs index 44bc252..a0b6342 100644 --- a/src/ReC.Client/ReCClientHelpers.cs +++ b/src/ReC.Client/ReCClientHelpers.cs @@ -5,6 +5,7 @@ using System.Net.Http; using System.Net.Http.Json; using System.Threading; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; namespace ReC.Client { @@ -46,14 +47,34 @@ namespace ReC.Client public static JsonContent ToJsonContent(T payload) => JsonContent.Create(payload); /// - /// Throws a if the response indicates a non-success status code. + /// Logs the outcome of an HTTP response. Throws a when the + /// response indicates a non-success status code; otherwise writes an informational log entry + /// containing the request and response details. /// /// The HTTP response to inspect. + /// An optional logger used to record the outcome. May be . /// A token to cancel the operation. - public static async Task EnsureSuccessAsync(HttpResponseMessage response, CancellationToken cancel = default) +#if NETFRAMEWORK + public static async Task HandleResponseAsync(HttpResponseMessage response, ILogger logger = null, CancellationToken cancel = default) +#else + public static async Task HandleResponseAsync(HttpResponseMessage response, ILogger? logger = null, CancellationToken cancel = default) +#endif { + var request = response.RequestMessage; + var method = request?.Method?.Method; + var uri = request?.RequestUri; + var statusCode = (int)response.StatusCode; + if (response.IsSuccessStatusCode) + { + logger?.LogInformation( + "ReC API request succeeded. {Method} {Uri} -> {StatusCode} ({ReasonPhrase})", + method, + uri, + statusCode, + response.ReasonPhrase); return; + } #if NETFRAMEWORK string body = null; @@ -76,11 +97,7 @@ namespace ReC.Client } } - var request = response.RequestMessage; - var method = request?.Method?.Method; - var uri = request?.RequestUri; - - var message = $"ReC API request failed with status {(int)response.StatusCode} ({response.ReasonPhrase}). " + var message = $"ReC API request failed with status {statusCode} ({response.ReasonPhrase}). " + $"{method} {uri}" + (string.IsNullOrWhiteSpace(body) ? string.Empty : $": {body}");