How do you log the HTTP Requests that the Kentico Kontent .NET delivery API here: https://github.com/Kentico/kontent-delivery-sdk-net
Specifically what I am looking for is how to log the HTTP Get requests to delivery.kentico.ai (the end point that you retrieve your content JSON from).
You can enrich and inject an HttpClient
to the DeliveryClient
.
Enrich:
public class LoggingHandler : DelegatingHandler
{
public LoggingHandler(HttpMessageHandler innerHandler, Microsoft.Extensions.Logging.ILogger logger)
: base(innerHandler)
{
Logger = logger;
}
public Microsoft.Extensions.Logging.ILogger Logger { get; }
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Logger.LogInformation(request.Method + " " + request.RequestUri);
HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
Logger.LogInformation(response.StatusCode + " " + response.Content.Headers);
return response;
}
}
Use e.g. Serilog
services.AddLogging(builder =>
{
// Add Serilog
builder.AddSerilog(new LoggerConfiguration()
.MinimumLevel.Information()
.WriteTo.File("logs\\log.log", rollingInterval: RollingInterval.Day)
.CreateLogger());
});
var serviceProvider = services.BuildServiceProvider();
var logger = serviceProvider.GetRequiredService<ILogger<Startup>>();
HttpClient httpClient = new HttpClient(new LoggingHandler(new HttpClientHandler(), logger));
var deliveryOptions = new DeliveryOptions();
Configuration.GetSection(nameof(DeliveryOptions)).Bind(deliveryOptions);
Inject:
var deliveryClient = DeliveryClientBuilder
.WithOptions(_ => deliveryOptions)
.WithHttpClient(httpClient)
.Build();
Additional resources: