Can I use ILoggerFactory in ASP.NET MVC 5 (not mvc core) project?
All of the Microsoft.Extensions.*
types, including the Logging system, are usable outside of ASP.NET Core. In fact, they're used in Entity Framework Core, which is not part of ASP.NET Core.
To use it in any app, just new
up the types you need to use and start calling them - there's nothing magical about it. And, of course, because it's not in an ASP.NET Core app, you don't get automatic dependency injection (DI) (because ASP.NET Core is what wires that up).
In the case here, it's probably simplest to use LoggerFactory
directly and all the APIs that come from that.
In fact, if you look at the unit tests for many of the types in Logging, they have a pattern that is similar to what you would do when not using DI:
https://github.com/aspnet/Logging/blob/9f642fd125b723b0cd3bbfd7d6bb58f7daee233f/test/Microsoft.Extensions.Logging.Test/LoggerTest.cs#L114-L120
That code creates a logger factory, adds a logger provider (you can use Console, EventLog, custom, etc.), and then logs an Information message to it:
var loggerFactory = new LoggerFactory();
var logger = loggerFactory.CreateLogger("Test");
loggerFactory.AddProvider(new CustomLoggerProvider("provider1", ThrowExceptionAt.None, store));
// Act
logger.LogInformation("Hello");
Just a side note here, if you are using Visual Studio 2015 or lower, you might have problem installing Microsoft.Extensions.Logging
Nuget package as this package require Nuget Version 4.3.0 or higher...
In order to install Microsoft.Extensions.Logging you need to install: https://dist.nuget.org/visualstudio-2015-vsix/v3.6.0/NuGet.Tools.vsix on Visual Studio 2015, or upgrade to Visual Studio 2017.
Also, Microsoft.Extensions.Logging
does not install on .Net 4.5, you need .Net 4.6.1 or higher.