vendredi 29 mai 2015

nlog logging pattern for common behaviour

I use loggin in my operation service class this way

   public class   MyServiceImplementation : IServiceInterface
    {
           static Logger log = LogManager.GetCurrentClassLogger();

           public bool A()
           {
              try
              {
                 log.Trace("Started");                 
                 // Do something A
                 log.Trace("Completed");
                 return true;
              }
              catch( Exception e )
              {
                  log.Error(e);               
              }
              return false;
           }


           public bool B()
           {
              try
              {
                 log.Trace("Started");                 
                 // Do something B
                 log.Trace("Completed");
                 return true;
              }
              catch( Exception e )
              {
                  log.Error(e);
              }
              return false;
           }
    }

As result in log i see pretty records as

MyServiceImplementation:B   Started
MyServiceImplementation:B   Completed
MyServiceImplementation:A   Started
MyServiceImplementation:A   Completed

But at look of code design it's not pretty because of duplication of logic, and i want to write as

   public class   MyServiceImplementation : IServiceInterface
    {
           static Logger log = LogManager.GetCurrentClassLogger();

           private bool CallMethod( Action m )
           {
              try
              {
                 log.Trace("Started");                 
                 m();
                 log.Trace("Completed");
                 return true;
              }
              catch( Exception e )
              {
                  log.Error(e);               
              }
              return false;

           }

           public bool A()
           {
              return CallMethod(()=> { //Do Something A  } )
           }

           public bool A()
           {
              return CallMethod(()=> { //Do Something B  } )
           }


    }

but in this case i lost stacktrace in log and information about A or B method is calling losted, i see CallMethod in all cases

MyServiceImplementation:CallMethod   Started
MyServiceImplementation:CallMethod   Completed
MyServiceImplementation:CallMethod   Started
MyServiceImplementation:CallMethod   Completed

How to take two goals - pretty logging and pretty code ?

Aucun commentaire:

Enregistrer un commentaire