I see a lot of posts mentioning usage of Microsoft.Extensions.Logging together with NLog.
I'd like to better understand what Microsoft.Extensions.Logging is used for?
And specifically why is it needed or what's the benefit of using it together with NLog?
Extensions. Logging provided by ASP.NET Core. This provides an ILogger interface that allows the provider of your choice to be used while minimizing the impact to existing code.
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.
Logging makes it possible to use NLog together with Microsoft ILogger-abstraction and Dependency Injection. It provides extension methods to register NLog as LoggingProvider for Microsoft Extension Logging using AddNLog() or UseNLog() . Note if using ASP.NET Core then instead install NLog.
NLog supports semantic/structured logging known from similar frameworks like Serilog and Microsoft. Extensions. Logging. With structured logging, you no longer log just simple text messages.
With NLog you could do:
var logger = NLog.LogManager.GetCurrentClassLogger(); logger.Info("Hello {Name}", "Earth");
That works for all platforms and all frameworks.
With .NET Core, Microsoft introduced the ILogger abstraction from Microsoft.Extensions.Logging. You could use that logging abstraction in your project and integrate it with NLog.
For example in ASP.NET Core you could inject Microsoft.Extensions.Logging.ILogger<HomeController>
and that could send the logs to NLog. (see Getting started with ASP.NET Core 2 · NLog/NLog Wiki)
using Microsoft.Extensions.Logging; public class HomeController : Controller { private readonly ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger) { _logger = logger; } public IActionResult Index() { _logger.LogInformation("Index page says hello {Name}", "Universe"); return View(); }
For NLog and Microsoft.Extensions.Logging there are the following packages:
Pros of using NLog directly
Logger.WithProperty(..)
Pros of using NLog via Microsoft.Extensions.Logging:
Update: added - Using NLog with appsettings.json
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