Created
February 16, 2023 13:31
-
-
Save mocella/74cbd7b46a14eb23bde02e2072c01a6b to your computer and use it in GitHub Desktop.
.NET HttpClient Delegating Handler to Log Request/Response details
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class HttpClientLoggingHandler: DelegatingHandler | |
{ | |
private readonly ILogger _logger; | |
public HttpClientLoggingHandler(ILogger logger) | |
{ | |
_logger = logger; | |
InnerHandler = new HttpClientHandler(); | |
} | |
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, | |
CancellationToken cancellationToken) | |
{ | |
var requestLog = new StringBuilder(); | |
requestLog.AppendLine($"{Environment.NewLine}REQUEST Uri: {request.RequestUri} - HttpMethod: {request.Method}"); | |
try | |
{ | |
var content = request.Content; | |
string jsonContent = await content!.ReadAsStringAsync(cancellationToken); | |
// note: may need a strategy to filter sensitive info from these payloads | |
requestLog.AppendLine($"REQUEST Body : {jsonContent}"); | |
} | |
catch (Exception) | |
{ | |
requestLog.AppendLine($"REQUEST Body : N/A"); | |
} | |
var response = await base.SendAsync(request, cancellationToken); | |
requestLog.AppendLine($"RESPONSE Status: {response.StatusCode}"); | |
try | |
{ | |
var content = response.Content; | |
string jsonContent = await content!.ReadAsStringAsync(cancellationToken); | |
// note: may need a strategy to filter sensitive info from these payloads | |
requestLog.AppendLine($"RESPONSE Body : {jsonContent}"); | |
} | |
catch (Exception) | |
{ | |
requestLog.AppendLine($"RESPONSE Body : N/A"); | |
} | |
_logger.LogInfo(requestLog.ToString(), "HttpClientLoggingHandler"); | |
return response; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// in cases where dependency injection aren't practical: | |
.... | |
var httpClient = new HttpClient(new HttpClientLoggingHandler(_logger)); | |
.... |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// assumes FooService has a constructor receiving HttpClient | |
builder.Services.AddHttpClient<FooService>() | |
.AddHttpMessageHandler<HttpClientLoggingHandler>(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment