c# - Initializing a log object for all classes -


i have winforms application lot's of classes, , in every class need write log if goes wrong.

today made logger function initialize in every class object using inside.

for example have main logic class have log , 1 more class that's running different logic should have log.

today using:

  • initialize log object in class contractor working it.
  • passing log object contractor.

what best architecture initialize 1 time , use in every class (not doing static).

my logger class:

namespace mylogger {     public class logger : imessagelogger     {         imessagelogger _messagelogger;          public logger(imessagelogger messagelogger)         {             _messagelogger = messagelogger;         }          public void log(string message)         {             _messagelogger.log(message);         }     }      public interface imessagelogger     {         void log(string message);     }      public class filelogger : imessagelogger     {         string _filepath = environment.currentdirectory;          public string filepath         {             { return _filepath; }             set { _filepath = value; }         }          public filelogger(string filepath)         {             _filepath = filepath;         }          public void log(string message)         {             string strfilename = path.combine(_filepath, string.format("{0}{1}.log", _filepath, datetime.now.tostring("yyyymmdd")));              using (streamwriter writer = new streamwriter(strfilename, true))             {                 writer.writeline(datetime.now.tostring("[dd/mm/yyyy hh:mm:ss]") + "  ->  " + message);             };         }     }      public class consolelogger : imessagelogger     {         public void log(string message)         {             console.writeline(message);         }     }  } 

i believe best way implement via dependencyinjection, should read online. if want quick , easy solution, implement singleton pattern logger, such -

public class logger : imessagelogger {     private imessagelogger _messagelogger;     private static logger _instance;      public static logger instance     {                 {             if (_instance == null)             {                 // pick one:                 _instance = new logger(new filelogger("somepath"));                 _instance = new logger(new consolelogger());             }              return _instance;         }     }      private logger(imessagelogger messagelogger)     {         _messagelogger = messagelogger;     }      public void log(string message)     {         _messagelogger.log(message);     } } 

and write log use line -

logger.instance.log("this log message!"); 

Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -