Skip to content

Logging in .NET Core Console Applications

Last updated on 2021-10-12

(Updated after David correctly pointed out that I was missing the Microsoft.Extensions.Logging.Console package. Sorry for all of you who wasted time trying to get this to run without this 🙏)

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 get started by creating a new console app:

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

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 =>
    var logger = loggerFactory.CreateLogger<Program>();
    logger.LogInformation("Hello World!");

Running the app prints the log entry to the console:

> dotnet run
info: Program[0]

Yes. It’s that simple.

Published inProgramming


  1. Perhaps I started with a different .NET Core Console template? I had to install the nuget package Microsoft.Extensions.Logging.Console in order to get the AddConsole() extension method. But your code worked great, thank!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.