HttpLoggingHandler Class
Namespace: System.Net.Http
Represents an HTTP handler that logs HTTP request and response messages.
Syntax
public class HttpLoggingHandler : DelegatingHandler
Remarks
The HttpLoggingHandler class is a type of DelegatingHandler that intercepts outgoing HTTP requests and incoming HTTP responses. It allows you to log the details of these messages, which can be invaluable for debugging, monitoring, and understanding network traffic.
This handler is particularly useful for scenarios where you need to inspect the headers, content, and other properties of HTTP messages without modifying the core request/response processing logic. You can configure the logging behavior by overriding the LogRequest and LogResponse methods.
To use HttpLoggingHandler, you typically chain it with other HttpClientHandler instances within an HttpClient's message handler pipeline.
Constructors
-
public HttpLoggingHandler()
Initializes a new instance of the
HttpLoggingHandlerclass with default settings. -
public HttpLoggingHandler(HttpMessageHandler innerHandler)
Initializes a new instance of the
HttpLoggingHandlerclass with a specified inner handler.Parameters:
innerHandler: The inner handler to pass requests to.
Methods
-
protected virtual void LogRequest(HttpRequestMessage request)
Logs the details of an outgoing HTTP request.
This method can be overridden to customize the request logging behavior. By default, it logs basic information such as the request URI and method.
Parameters:
request: TheHttpRequestMessageto log.
-
protected virtual void LogResponse(HttpResponseMessage response)
Logs the details of an incoming HTTP response.
This method can be overridden to customize the response logging behavior. By default, it logs basic information such as the status code and reason phrase.
Parameters:
response: TheHttpResponseMessageto log.
-
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
Sends an HTTP request to the inner handler to send to the server.
This method intercepts the request, calls
LogRequest, sends the request to the inner handler, receives the response, callsLogResponse, and then returns the response.Parameters:
request: The HTTP request message to send.cancellationToken: A cancellation token to cancel the operation.
Returns:
An instance of the
HttpResponseMessageclass.
Example
Here's a basic example of how to use HttpLoggingHandler:
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
public class CustomLoggingHandler : HttpLoggingHandler
{
protected override void LogRequest(HttpRequestMessage request)
{
Console.WriteLine($"--- Request ---");
Console.WriteLine($"Method: {request.Method}");
Console.WriteLine($"URI: {request.RequestUri}");
if (request.Headers.Count > 0)
{
Console.WriteLine($"Headers:");
foreach (var header in request.Headers)
{
Console.WriteLine($" {header.Key}: {string.Join(", ", header.Value)}");
}
}
Console.WriteLine("---------------");
}
protected override void LogResponse(HttpResponseMessage response)
{
Console.WriteLine($"--- Response ---");
Console.WriteLine($"Status Code: {(int)response.StatusCode} {response.ReasonPhrase}");
if (response.Headers.Count > 0)
{
Console.WriteLine($"Headers:");
foreach (var header in response.Headers)
{
Console.WriteLine($" {header.Key}: {string.Join(", ", header.Value)}");
}
}
Console.WriteLine("----------------");
}
}
public class Example
{
public static async Task Main(string[] args)
{
var loggingHandler = new CustomLoggingHandler();
var httpClientHandler = new HttpClientHandler();
loggingHandler.InnerHandler = httpClientHandler; // Chain the handlers
using (var client = new HttpClient(loggingHandler))
{
try
{
var response = await client.GetAsync("https://www.example.com");
response.EnsureSuccessStatusCode(); // Throw if HTTP status is an error
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine("Successfully retrieved content.");
}
catch (HttpRequestException e)
{
Console.WriteLine($"Request error: {e.Message}");
}
}
}
}