简体   繁体   English

使用静态属性隐藏NLog返回类实例

[英]Hiding NLog With static property returning class instance

I am trying to break away direct dependency of NLog from my code. 我试图摆脱我的代码对NLog的直接依赖。 So if in the future i decided to use another logging library, it will be painless. 因此,如果将来我决定使用另一个日志记录库,它将很轻松。 What I did is as following, 我所做的如下

 internal class Logger
{
    private NLog.Logger _NLogInstance;

    internal static Logger Instance
    {
        get
        {
            return new Logger();
        }
    }

    public Logger()
    {
        LogManager.ReconfigExistingLoggers();
        _NLogInstance = LogManager.GetCurrentClassLogger();
    }

    public void Trace(string message)
    {
        _NLogInstance.Trace(message);
    }

    public void Debug(string message)
    {
        _NLogInstance.Debug(message);
    }

    public void Info(string message)
    {
        _NLogInstance.Info(message);
    }

    public void Warn(string message)
    {
        _NLogInstance.Warn(message);
    }

    public void Error(Exception ex, string message)
    {
        _NLogInstance.Error(ex, message);
    }

    public void Fatal(Exception ex, string message)
    {
        _NLogInstance.Fatal(ex, message);
    }
}

As you can see, to use my Logger one only need to do so, 如您所见,只需使用Logger,

Logger.Instance.Fatal(ex, ex.Message);

So, the real implementation of NLog is somehow hidden from the user of Logger. 因此,NLog的真正实现对Logger用户而言是隐藏的。 If tomorrow I need to use Log4net, i will only need to change my implementation in Logger class. 如果明天我需要使用Log4net,则只需更改Logger类中的实现即可。

Is there any potential problem of doing so? 这样做有潜在的问题吗? Because I don't see people doing this anywhere. 因为我看不到有人在任何地方这样做。 Or are there any better way? 还是有更好的方法?

I totally agree with the comments. 我完全同意这些意见。 You probably won't need to switch to another logging library and if you do, it's because the new library is so clever and works in another way, why you will need to change your abstraction anyway. 您可能不需要切换到另一个日志记录库,如果这样做,是因为新的库非常聪明,并且以另一种方式工作,因此无论如何您都需要更改抽象。

If you insist on wrapping you Common Logging .NET instead. 如果您坚持要包装您的Common Logging .NET It's an abstraction on top of pretty much all of the major logging frameworks. 它是几乎所有主要日志记录框架之上的抽象。 This way you don't need to write the abstraction yourself. 这样,您无需自己编写抽象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM