Reputation: 15091
I have read this but it is for asp.net core. My code below is for a non-web console app. Visual Studio tells me that AddConsole(this ILoggerFactory,...)
is obsolete and must be replaced by AddConsole(this ILoggingBuilder,...)
.
class Program
{
static void Main(string[] args)
{
ILoggerFactory ilf = new LoggerFactory();
ilf.AddConsole(LogLevel.Information);
ILogger<Program> logger = ilf.CreateLogger<Program>();
logger.LogError("the cpu is overheating");
Console.WriteLine("waiting for logger to print");
}
}
How to use the extension method AddConsole
for ILoggingBuilder
instead of ILoggerFactory
in the above case?
Upvotes: 5
Views: 3643
Reputation: 4859
The shortest one is
var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());
Upvotes: 2
Reputation: 77876
You should be calling the CreateDefaultBuilder()
method on WebHost
like below. See this for more information https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-2.2
public static void Main(string[] args)
{
var host = CreateWebHostBuilder(args).Build();
var logger = host.Services.GetRequiredService<ILogger<Program>>();
logger.LogInformation("the cpu is overheating");
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.AddConsole();
});
If it's a console app, then probably you can just say
ILogger<Program> logger = new Logger<Program>(new LoggerFactory());
logger.LogError("System is over heated!!!");
That's not too difficult either, you need to extend ILoggerProvider
and pass your custom provider to logger factory like
new LoggerFactory().AddProvider(new CustomProvider());
See this blog post with nice example for color console logging https://asp.net-hacker.rocks/2017/05/05/add-custom-logging-in-aspnetcore.html
Upvotes: 1