Skip to content

Instantly share code, notes, and snippets.

@ylorph
Created Sep 22, 2020
Embed
What would you like to do?
DI Tuesday ( enable logging of http client in a plain old console app)
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace DITuesday
{
// Need references to :
// Microsoft.Extensions.DependencyInjection
// Microsoft.Extensions.Http
// Microsoft.Extensions.Logging.Console
class Program
{
static async Task Main(string[] args)
{
var services = new ServiceCollection();
services.AddHttpClient();
services.AddLogging(b =>
{
b.AddFilter("System.Net.Http", LogLevel.Trace);
b.AddConsole();
});
var provider = services.BuildServiceProvider();
var factory = provider.GetRequiredService<IHttpClientFactory>();
var client = factory.CreateClient();
var resp= await client.GetAsync("https://www.google.com");
Console.WriteLine(resp.StatusCode);
}
}
}
@ylorph
Copy link
Author

ylorph commented Sep 22, 2020

ALternatives:
var logger = LoggerFactory
.Create(logBuilder =>
{
logBuilder.AddFilter("System.Net.Http", LogLevel.Trace);
logBuilder.AddConsole();
})
.CreateLogger();
var handler = new LoggingHttpMessageHandler(logger)
{
InnerHandler = new SocketsHttpHandler()
};
var httpClient = new HttpClient(handler);
var response = await httpClient.GetAsync("https://www.google.com");
logger.LogInformation(response.StatusCode.ToString());

https://github.com/ilya-chumakov/LoggingAdvanced
var consoleLogger = new AdvancedConsoleLogger("client", (_, __) => true, new ConsoleLoggerSettings());
var handler = new LoggingHttpMessageHandler(consoleLogger)
{
InnerHandler = new SocketsHttpHandler()
};
var httpClient = new HttpClient(handler);
var response = await httpClient.GetAsync("https://www.google.com");
consoleLogger.LogInformation(response.StatusCode.ToString());

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment