简体   繁体   中英

How to log to console in c#

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM