Implementing and using the logger shell for Microsoft.Extensions.Logging

This question is related to Steven s answer - here . He offered very good packaging for the logger. I will insert 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 correct way to create an 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 log4net question , but is now specific to Microsoft.Extensions.Logging.

+2
c # logging ms-extensions-logging
Sep 21 '16 at 7:27
source share
1 answer

So my question is what is the correct way to create an implementation that proxies Microsoft.Extensions.ILogger?

you should create something like:

 public sealed class MicrosoftLoggingAdapter : ILogger { private readonly Microsoft.Extensions.ILogger adaptee; public MicrosoftLoggingAdapter (Microsoft.Extensions.ILogger adaptee) => this.adaptee = adaptee; public void Log(LogEntry e) => adaptee.Log(ToLevel(e.Severity), 0, e.Message, e.Exception, (s, _) => s); private static LogLevel ToLevel(LoggingEventType s) => s == LoggingEventType.Debug ? LogLevel.Debug : s == LoggingEventType.Information ? LogLevel.Information : s == LoggingEventType.Warning ? LogLevel.Warning : s == LoggingEventType.Error ? LogLevel.Error : LogLevel.Critical; } 

What is the best way to use it later in code?

If you are using a DI container, just use the DI container to display the ILogger in the MicrosoftLoggingAdapter . You also need to register Microsoft.Extensions.ILogger or simply provide an instance of the MS registrar for the DI container to enter it into the MicrosoftLoggingAdapter constructor.

If you are not using a DI container, that is, using Pure DI , you are doing something like this:

 var logger = loggerFactory.CreateLogger("Application"); ILogger logging_adapter = new MicrosoftLoggingAdapter(logger); var myobject = new MyClass(other_dependencies_here, logging_adapter); 
+4
Sep 21 '16 at 7:27
source share



All Articles