5

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");
    }
}

Question

How to use the extension method AddConsole for ILoggingBuilder instead of ILoggerFactory in the above case?

Second Person Shooter
  • 14,188
  • 21
  • 90
  • 165

2 Answers2

2

The shortest one is

var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());
d_f
  • 4,599
  • 2
  • 23
  • 34
1

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

Rahul
  • 76,197
  • 13
  • 71
  • 125