c# - Suggest design: almost every object in app has loggger -


i'm writing application. use nlog logging. in application every object can write log. define protected member that:

protected logger logger;  protected virtual logger logger {      { return logger ?? (logger = logmanager.getlogger(this.gettype().tostring())); } } 

in case need copy/paste code every base class in application. or see other option: define app-specific root object logger in , subclass it. semantically sounds wrong because not true "is-a" situation me.

are there better options?

sometimes wish c# support multiple inheritance or mixins....

you write extension method:

public static logger logger(this object obj) {     return logmanager.getlogger(obj.gettype()); } 

the drawback bit slower created instance not cached (except internally in nlog, implementation detail), yourself:

public static logger logger(this object obj) {     logger logger;     type type = obj.gettype();     // s_loggers static dictionary<type, logger>     if (!s_loggers.trygetvalue(type, out logger)) { // not in cache         logger = logmanager.getlogger(type);         s_loggers[type] = logger;  // cache     }     return logger; } 

than can call this:

this.logger.log(...) 

the obvious drawback object write logger of other object.

with regard comment memory leak (now deleted):

the first implementation solves that. however, not leak more static object. leak if not access these objects. alternative cache weakreference logger instead of logger itself, see no point, believe there caching in nlog itself. otherwise, nlog have create new instance of logger each type.


Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

java.lang.NoClassDefFoundError When Creating New Android Project -

Decoding a Python 2 `tempfile` with python-future -