Created
September 22, 2020 14:16
DI Tuesday ( enable logging of http client in a plain old console app)
This file contains 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
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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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());