微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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);

原文地址:https://www.jb51.cc/csharp/92490.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐