using System.Threading.Tasks;
using System.Collections.Generic;
public static async Task Main()
var httpClient = new HttpClient();
var logger = new HttpLogger(httpClient);
var request = new HttpRequestMessage(HttpMethod.Get, "https://jsonplaceholder.typicode.com/posts/1");
await logger.SendRequestAsync(request);
private readonly HttpClient _httpClient;
public HttpLogger(HttpClient httpClient)
_httpClient = httpClient;
public async Task<string> SendRequestAsync(HttpRequestMessage request)
HttpResponseMessage response = await _httpClient.SendAsync(request);
if (!response.IsSuccessStatusCode)
var logData = await GenerateLogAsync(request, response);
string logJson = JsonSerializer.Serialize(logData);
Console.WriteLine("Error Log:\n" + logJson);
throw new HttpRequestException($"Request failed with status code: {response.StatusCode}");
return await response.Content.ReadAsStringAsync();
Console.WriteLine("Exception occurred: " + ex.Message);
private async Task<Dictionary<string, object>> GenerateLogAsync(HttpRequestMessage request, HttpResponseMessage response)
var log = new Dictionary<string, object>
["Request"] = new Dictionary<string, object>
["Method"] = request.Method.Method,
["RequestUri"] = request.RequestUri.ToString(),
["Headers"] = FormatHeaders(request.Headers),
["Body"] = request.Content != null ? await request.Content.ReadAsStringAsync() : null
["Response"] = new Dictionary<string, object>
["StatusCode"] = (int)response.StatusCode,
["ReasonPhrase"] = response.ReasonPhrase,
["Headers"] = FormatHeaders(response.Headers),
["Body"] = response.Content != null ? await response.Content.ReadAsStringAsync() : null
private Dictionary<string, string> FormatHeaders(IEnumerable<KeyValuePair<string, IEnumerable<string>>> headers)
var formattedHeaders = new Dictionary<string, string>();
foreach (var header in headers)
formattedHeaders[header.Key] = string.Join(", ", header.Value);