How to log to console in c#

Viewed 8079

I want to use Microsoft.Extensions.Logging in order to log stuff to the console. I have set it up like this:

static void Main()
{
    ILoggerFactory loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());
    ILogger logger = loggerFactory.CreateLogger<Program>();
    logger.LogInformation("Current directory {0}", Directory.GetCurrentDirectory());
}

However, nothing is written to the console.

2 Answers

The problem is that the ConsoleLoggerProvider, which is added to the loggerFactory by AddConsole, is IDisposable and must be disposed of, in order to flush the output. Disposing of the loggerFactory will accomplish that. So either call loggerFactory.Dispose() at the end of the program or add using when creating the loggerFactory like so:

static void Main()
{
    using ILoggerFactory loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());
    ILogger logger = loggerFactory.CreateLogger<Program>();
    logger.LogInformation("Current directory {0}", Directory.GetCurrentDirectory());
}

I think the easiest way to accomplish this (without using the GenericHost) is using the ServiceCollection standalone.

public static void Main()
{
    var collection = new ServiceCollection();
    collection.AddLogging(b => {
        b.AddConsole();
        b.SetMinimumLevel(LogLevel.Information);
    });
    var sp = collection.BuildServiceProvider();

    using(var scope = sp.CreateScope())
    {
        var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
        logger.LogInformation("Current directory {0}", Directory.GetCurrentDirectory());
    }
}

.netfiddle example

Related