title: Using delegates or interfaces to decouple the logging - Best practices - C#
body: <p>My solutions has several projects which includes several libraries and one project for UI. Currently it is a windows forms application and I use log4net for logging. This UI project has only reference to log4net and this project maintains the configuration files. But I would like to log from my libraries as well. </p>
  
  <p>Usual method for doing this is to wrap the logging calls behind an interface. Create a common project something called utilities and add this interface to this project. Now this project can be used in all the projects and can use this interface for logging.</p>
  
  <p>I am thinking about an alternative design which involves passing delegates and reducing coupling and avoiding unnecessary interfaces. </p>
  
  <p>Consider following class is one from my library.</p>
  
  <pre><code>public sealed class Foo
  {
      Action&lt;string&gt; log;
      Action&lt;string, Exception&gt; logException;
  
      public Foo(Action&lt;string&gt; log, Action&lt;string,Exception&gt; logException)
      {
          this.log = log;
          this.logException = logException;
      }
  
      public void Work()
      {
          WL("Starting work");
          WL("Completed step1");
          .........
      }
  
      void WL(string message)
      {
          if(log != null) log(message);
      }
  
      void WL(string message, Exception exception)
      {
          if(logException != null) logException(message, exception);
      }
  }
  </code></pre>
  
  <p>Now from the calling code, I can easily pass the logging method. Something like</p>
  
  <pre><code>Foo foo = new Foo(message =&gt; Console.WriteLine(message), 
                  (message, exception) =&gt; Console.WriteLine("{0},{1}", message, exception));
  foo.Work();
  </code></pre>
  
  <p>Used a console for explaining, in reality I will use the logging code here.</p>
  
  <p>1 - Do you think this as a better solution? I think this is better as this is more loosely coupled. </p>
  
  <p>2 - Is there any other better solutions available?</p>
  
  <p><a href="https://stackoverflow.com/questions/522370/dependency-injection-and-logging-interfaces">This</a> is the only related question I have found here</p>
  
  <p>Any thoughts...?</p>