c# - Proper way to extend class/method functionality - using NLog as example -


i'm using nlog .net logging library here example; question isn't specific nlog.

typical nlog logging looks this:

private static logger log = logmanager.getlogger("logger_name"); log.info("some log message"); 

i want add functionality info() method. perhaps want timestamp added log message.

the way i've accomplished absolutely horrendous , stinks of code smell.

i created helper class holds logger instance, implements it's own (but named same) getlogger() , info() methods (ugh, terrible), , includes custom functionality in info().

public static class nloglogmanagerhelper // can't derive logmanager because it's sealed {     public static string _loggername;     public static nlog.logger _log;      public static nlog.logger getlogger(string loggername)     {         _loggername = loggername;         _log = logmanager.getlogger(loggername);         return _log;     }      public static void info(string message)     {         var eventinfo = new logeventinfo(loglevel.info, _loggername, message);         // add custom functionality         eventinfo.properties["mytimestamp"] = time.convertutctoest(datetime.utcnow);         _log.log(eventinfo);     } } 

i'm not sure taking approach of making helper , wrapping logger right approach.

this "works" stinky heck. 1 big stink it's nlog's logger class has info() methods, create mylogger inherits logger, can't implement info() because it's not overridable. stink since i've duplicated info() method don't have access of it's overloads. i'd know proper way approach problem, whether it's oo approach, or design pattern, or whatever.

there @ least 1 definite code smell, , calling getlogger() method different loggername values overwrite both static string _loggername , static nlog.logger _log (which should both private, way), meaning in such case can't subsquently call info() method in reliable way.

you might better use extension method on nlog.logger instance created regular way. extension methods great way of making extending class, if in reality can't, , @ same time never having mention static class (just add using-line namespace).

public static class nloghelper {     public static void stampedinfo(this nlog.logger logger, string message)     {         var eventinfo = new logeventinfo(loglevel.info, logger.name, message);         eventinfo.properties["mytimestamp"] = time.convertutctoest(datetime.utcnow);         logger.log(eventinfo);     } }  // usage: //   var log = logmanager.getlogger(loggername); //   log.stampedinfo("message"); 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -