c# – log4net的logger包装器的实现和使用

这个问题与 Steven的回答有关 – 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的实现的正确方法是什么?我应该只使用类型参数添加一个Log扩展方法,然后在里面创建一个开关吗?在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.

这是否意味着每个会记录的类(基本上都是每个)都应该在其构造函数中使用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,或者只是将一个log4net记录器实例提供给DI容器,以将其注入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);

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...