(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 => { builder.AddConsole(); }); var logger = loggerFactory.CreateLogger<Program>(); 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.