Skip to content
Andreas Gullberg Larsen edited this page Feb 14, 2015 · 2 revisions

PortableLog v2

Portable logging interface and adapters for the most common logging implementations. Heavily based on common-logging, but with a couple of improvements:

  • Move exception parameter first, better readability
  • Add CallingMemberName to auto-inject the method name
  • PortableLog.Core nuget with ILog, ILogFactory and a NoOpLogger to pass in to log producers, such as the portable view models of a cross-platform app
  • PortableLog.NLog nuget with NLogFactory and NLogLogger adapter, to hook up in WPF, WinForms and WinStore. To my knowledge NLog does not yet work with Xamarin for iOS and Android, but adapters for other logging frameworks can easily be added. Pull requests are welcome.

Log Adapters

  • NLogLogger (PortableLog.NLog nuget)
  • NoOpLogger (does nothing)

Example

public class MyClass
{
  private readonly ILog _log;
  
  public MyClass(ILogFactory logFactory)
  {
    _log = logFactory.GetLogger<MyClass>();
  }
  
  public void MyMethod()
  {
    try 
    {
      _log.Trace("On enter.");
   
      _log.Info("Simple log message.");

       // In v2 we removed the various Format method overloads to
       // achieve [CallerMemberName] support on all methods.
       // This means you need to format the strings yourselves, such as
       // using the With() string extension or string.Format() yourself.
      _log.Info("My name is {1}, {0} {1}.".With("James", "Bond"));

      // Use callbacks to skip CPU intensive logging when log level is disabled
      _log.Debug(h => h("The answer {0} took a long time to compute.", CalculateHeavyResult()));
    }
    catch (Exception e)
    {
      _log.Error(e, "Some error occurred.");
    }
    finally 
    {
      _log.Trace("On exit.");
    }
  }
}

Example log output:

  MyClass.MyMethod: On enter.
  MyClass.MyMethod: Simple log message.
  MyClass.MyMethod: My name is Bond, James Bond.
  MyClass.MyMethod: The answer 42 took a long time to compute.
  MyClass.MyMethod: On exit.

Clone this wiki locally