Implementing and using a registrar wrapper for Serilog

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 Serilog ?

Note: this question is related to this question about log4net , but is now specific to Serilog.

+1
c # logging serilog
Sep 14 '16 at 20:34
source share
1 answer

So my question is how to properly create an implementation that proxies Serilog?

you should create something like:

 public class SerilogAdapter : ILogger { private readonly Serilog.ILogger m_Adaptee; public SerilogAdapter(Serilog.ILogger adaptee) { m_Adaptee = adaptee; } public void Log(LogEntry entry) { if (entry.Severity == LoggingEventType.Debug) m_Adaptee.Debug(entry.Exception, entry.Message); if (entry.Severity == LoggingEventType.Information) m_Adaptee.Information(entry.Exception, entry.Message); else if (entry.Severity == LoggingEventType.Warning) m_Adaptee.Warning(entry.Message, entry.Exception); else if (entry.Severity == LoggingEventType.Error) m_Adaptee.Error(entry.Message, entry.Exception); else m_Adaptee.Fatal(entry.Message, entry.Exception); } } 

Does this mean that every class that will write sth (so basically everyone) should have an ILogger in its constructor?

As I understand it from Stevens: Yes, you must do it.

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 SerilogAdapter . You also need to register Serilog.ILogger or just provide an instance of the Serilog registrar in the DI container to insert it into the SerilogAdapter constructor.

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

 Serilog.ILogger log = Serilog.Log.Logger.ForContext("MyClass"); ILogger logging_adapter = new SerilogAdapter(log); var myobject = new MyClass(other_dependencies_here, logging_adapter); 
+3
Sep 14 '16 at 20:34
source share



All Articles