设计建议:几乎每一个应用程序对象有loggger [英] Suggest design: almost every object in app has loggger

查看:490
本文介绍了设计建议:几乎每一个应用程序对象有loggger的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写的应用程序。我使用的NLOG记录。在这种应用中,几乎每一个对象都可以写入日志。我定义受保护的成员为:

I'm writing an application. I use NLog for logging. In this application almost every object can write to log. I define protected member for that:

protected Logger logger;

protected virtual Logger Logger
{
     get { return logger ?? (logger = LogManager.GetLogger(this.GetType().ToString())); }
}

在这种情况下,我需要复制/粘贴此代码为每一个基类在应用程序。或者,我看其他的选项:定义与它记录仪应用程序特定的根对象和它的子类。但是从语义,因为它不是真正的是一个我的情况,这听起来是错误的。

In that case I need to copy/paste this code for every base class in application. Or I see other option: define app-specific root object with logger in it and subclass it. But semantically this sounds wrong because it is not true "is-a" situation for me.

还有没有更好的选择?

推荐答案

有时候,我真希望C#将支持多重继承或混入....

Sometimes I really wishes C# would support multiple inheritance or mixins....

您可以编写扩展方法:

public static Logger Logger(this object obj) {
    return LogManager.GetLogger(obj.GetType());
}



的缺点是,它会是慢一点作为创建的实例是不缓存的(除了在内部NLOG,这是一个实现细节),但你可以自己做:

The drawback is that it would be a bit slower as the created instance is not cached (except internally in NLog, which is an implementation detail), but you could do it yourself:

public static Logger Logger(this object obj) {
    Logger logger;
    Type type = obj.GetType();
    // s_loggers is static Dictionary<Type, Logger>
    if (!s_loggers.TryGetValue(type, out logger)) { // not in cache
        logger = LogManager.GetLogger(type);
        s_loggers[type] = logger;  // cache it
    }
    return logger;
}



比你可以这样调用它:

Than you can call it like this:

this.Logger.Log(...)

明显的缺点是,任何对象可以写信给任何其他对象的记录

The obvious drawback is that any object could write to logger of any other object.

关于关于内存泄漏(现已删除)发表评论:

With regard to comment about memory leak (now deleted):

第一批实施解决了。然而,这不是一个泄漏超过任何静态对象。这将是一个泄漏,如果你不能访问这些对象。正如你可以缓存替代的WeakReference 来记录仪,而不是记录器本身,但我没有看到一点,因为我相信已经有在NLOG本身的一些缓存。否则,NLOG总是必须创建记录器为每个类型的新实例

The first implementation solves that. However, it is not a leak more than any static object. It would be a leak if you could not access these objects. As an alternative you could cache WeakReference to logger instead of logger itself, but I see no point, as I believe that there already is some caching in NLog itself. Otherwise, NLog would always have to create a new instance of logger for each type.

这篇关于设计建议:几乎每一个应用程序对象有loggger的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆