It seems that Microsoft are really trying to shove DI down your throat with .NET Core, and I'm not sure why, but frankly my console app is small and simple and I just don't want to build a whole DI container just to do some simple logging. How can I do logging in .NET Core without using DI? Everything I've read assumed you're going to use .NET Core's built-in logging architecture which obviously requires DI, but there must be a way to just do it without DI using a static variable on the class?
NLog is one of the most popular, and one of the best-performing logging frameworks for . NET. Setting up NLog is fairly simple. Developers can use Nuget to download the dependency, then edit the NLog.
If you want to do it yourself you will need to instantiate a LoggerFactory instance somewhere and configure what providers you want. Then you just need to call CreateLogger to create a instance or use new Logger<T>(ILoggerFactory)
to create a logger.
using Microsoft.Extensions.Logging; static class MyLogger { public static ILoggerFactory LoggerFactory {get;} static MyLogger() { LoggerFactory = new LoggerFactory(); LoggerFactory.AddConsole(); } } public MyClass { private readonly ILogger _logger = new Logger<MyClass>(MyLogger.LoggerFactory); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With