Skip to content

Tag: logging

Logging in .NET Core Console Applications

Logging should be simple. It should come out of the box in any programming language + framework. I’ve seen too many developers use Console.WriteLine(...) as a way to log in their code because for some reason, wiring logging frameworks is complicated (at least feels complicated). So after reading a lot of documentation and blogs, I decided to share what I learned. This will at least help my future self in a couple of years :-).

Let’s start by creating a new console app and adding the required packages:

> mkdir DotNetCoreConsoleAppLogging
> cd .\DotNetCoreConsoleAppLogging\
> dotnet new console
> dotnet add package Microsoft.Extensions.Logging
> dotnet add package Microsoft.Extensions.Logging.Console

(and thanks to Sudhakar’s blog for finding the issue in the previous version of this blog and giving a fix)

For the simplest case, we create a logger by using a LoggerFactory to get a Logger instance, and write to the log which is directed to the console:

using Microsoft.Extensions.Logging;

public class Program
{
  public static void Main(string[] args)
  {
    using var loggerFactory = LoggerFactory.Create(builder =>
      {
        builder.AddConsole();
      });
    var logger = loggerFactory.CreateLogger();
    logger.LogInformation("Hello World!");
  }
}

Running the app prints the log entry to the console:

> dotnet run
info: Program[0]
Hello!

Yes. It’s that simple.