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

前端之家收集整理的这篇文章主要介绍了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.f2er.com/csharp/92490.html

猜你在找的C#相关文章