This question is related to Steven’s answer - here. He proposed a very good logger wrapper. I will paste his code below:
public interface ILogger
{
void Log(LogEntry entry);
}
public static class LoggerExtensions
{
public static void Log(this ILogger logger, string message)
{
logger.Log(new LogEntry(LoggingEventType.Information,
message, null));
}
public static void Log(this ILogger logger, Exception exception)
{
logger.Log(new LogEntry(LoggingEventType.Error,
exception.Message, exception));
}
// More methods here.
}
So, my question is what is the proper way to create implementation that proxies to Microsoft.Extensions.Logging and what is the best way to use it later in the code?
Note: this question is a copy of this question about log4net but now specific to Microsoft.Extensions.Logging.
Here is my solution. Not too unlike Steven's. But not exactly like it. And mine leans toward dotNetCore, but the same thing can be accomplished in dotnetFW.
DotNetCoreLogger is the concrete of "MY" ILogger. And I inject the "microsoft" ILogger (Microsoft.Extensions.Logging.ILogger) into "My" concrete logger.
There is another SOF answer that "inspired" "my" logging abstraction....and after going from DotNetFramework (classic) to DotNotCore, I am so glad I did a "my" ILogger abstraction.
you should create something like:
If you are using a DI container, then just use the DI container to map
ILogger
toMicrosoftLoggingAdapter
. You also need to registerMicrosoft.Extensions.ILogger
, or just give an instance of MS logger to the DI container to inject it to the MicrosoftLoggingAdapter constructor.If you don't use a DI container, i.e., you use Pure DI, then you do something like this: