Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging in .NET Core without DI?

Tags:

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?

like image 297
Jez Avatar asked Nov 10 '18 02:11

Jez


People also ask

Which logging framework is best for .NET Core?

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.


1 Answers

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); } 
like image 89
Scott Chamberlain Avatar answered Sep 19 '22 19:09

Scott Chamberlain