Implementing and using the logger shell for log4net

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: how to create an implementation whose proxy server is connected to log4net ? Should I just add another log extension method with a type parameter and then create a switch inside? Use another log4net method in case of LoggingEventType ?

And the second question, what is the best way to use it later in the code?

Because he wrote:

(...) you can easily create an implementation of ILogger (...) and configure your DI container to inject it into classes that have an ILogger constructor.

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

+6
c # logging log4net nlog
Sep 01 '15 at 23:16
source share
1 answer

So my question is, what is the correct way to create an implementation that has proxies for log4net?

you should create something like:

 public class Log4netAdapter : ILogger { private readonly log4net.ILog m_Adaptee; public Log4netAdapter(log4net.ILog adaptee) { m_Adaptee = adaptee; } public void Log(LogEntry entry) { //Here invoke m_Adaptee if(entry.Severity == LoggingEventType.Debug) m_Adaptee.Debug(entry.Message, entry.Exception); else if(entry.Severity == LoggingEventType.Information) m_Adaptee.Info(entry.Message, entry.Exception); else if(entry.Severity == LoggingEventType.Warning) m_Adaptee.Warn(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 ILogger in Log4netAdapter . You also need to register log4net.ILog or just provide an instance of log4net logger in the DI container to insert it into the Log4netAdapter constructor.

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

 ILog log = log4net.LogManager.GetLogger("MyClass"); ILogger logging_adapter = new Log4netAdapter(log); var myobject = new MyClass(other_dependencies_here, logging_adapter); 
+11
01 Sep '15 at 23:37
source share



All Articles