Skip to content

Logging in .NET Core Console Applications

Last updated on 2021-08-21

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

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();
    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

One Comment

Leave a Reply

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