2

Logging in .NET Core Console Applications

 2 years ago
source link: https://vainolo.com/2021/05/11/logging-in-net-core-console-applications/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Logging in .NET Core Console Applications

Published by vainolo on 2021-05-11

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 =>
{
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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK