log4net logger wrapper 的实现和使用

Implementation and usage of logger wrapper for log4net

此问题与 Steven’s answer - here 有关。他提出了一个非常好的记录器包装器。我将在下面粘贴他的代码:

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.
}

所以,我的问题是创建代理到 log4net 的实现的正确方法是什么?我应该只添加另一个带有类型参数的日志扩展方法,然后在里面创建一个开关吗?在 LoggingEventType ?

的情况下使用不同的 log4net 方法

第二个问题,稍后在代码中使用它的最佳方式是什么?

因为他写道:

(…) you can easily create an ILogger implementation (…) and configure your DI container to inject it in classes that have a ILogger in their constructor.

这是否意味着每个将记录某事的 class(基本上每个)都应该在其构造函数中包含 ILogger

So, my question is what is the proper way to create implementation that proxies to log4net?

您应该创建如下内容:

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 that mean that every class that will log sth (so basically every), should have ILogger in its constructor?

据我从史蒂文斯的回答中了解到:是的,你应该这样做。

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

如果您使用的是 DI 容器,那么只需使用 DI 容器将 ILogger 映射到 Log4netAdapter。你还需要注册log4net.ILog,或者只是给DI容器一个log4net logger的实例,将它注入到Log4netAdapter构造函数中。

如果您不使用 DI 容器,即您使用 Pure DI,那么您可以这样做:

ILog log = log4net.LogManager.GetLogger("MyClass");

ILogger logging_adapter = new Log4netAdapter(log);

var myobject = new MyClass(other_dependencies_here, logging_adapter);