建议设计:应用程序中几乎每个对象都有loggger [英] Suggest design: almost every object in app has loggger
问题描述
保护Logger记录器;
保护虚拟Logger Logger
{
get {return logger ?? (logger = LogManager.GetLogger(this.GetType()。ToString())); }
}
在这种情况下,我需要为每个基类复制/粘贴这段代码在应用中。或者我看到其他选项:使用记录器定义应用程序特定的根对象,并将其子类化。但是在语义上这听起来是错误的,因为它不是真的我是一个的情况。
有没有更好的选择?
有时我真的希望C#能支持多重继承或混合....
你可以写一个扩展名方法:
public static Logger Logger(此对象obj){
返回LogManager.GetLogger(obj.GetType() );
}
缺点是创建的实例不会慢一点缓存(除了NLog内部,这是一个实现细节),但是你可以自己做:
public static Logger Logger这个对象obj){
Logger logger;
Type type = obj.GetType();
// s_loggers是静态字典<类型,记录器>
if(!s_loggers.TryGetValue(type,out logger)){// not in cache
logger = LogManager.GetLogger(type);
s_loggers [type] = logger; // cache it
}
return logger;
}
比你可以这样调用:
this.Logger.Log(...)
明显的缺点是任何对象都可以写入任何其他对象的记录器。
关于内存泄漏(现已删除)的评论: p>
第一个实现解决了这个问题。但是,它不是任何静态对象的泄漏。如果您无法访问这些对象,那将是一个泄漏。作为替代方案,您可以将 WeakReference
缓存到记录器而不是记录器本身,但是我没有看到任何意见,因为我相信NLog本身已经有一些缓存。否则,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.
are there any better options?
Sometimes I really wish C# would support multiple inheritance or mixins....
You could write an extension method:
public static Logger Logger(this object obj) {
return LogManager.GetLogger(obj.GetType());
}
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):
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屋!