Search code examples
java.netloggingapache-commons

Logging Commons and Mapped Diagnostic Context


What have others done to get around the fact that the Commons Logging project (for both .NET and Java) do not support Mapped or Nested Diagnostic Contexts as far as I know?


Solution

  • For the sake of completeness, I ended up writing my own very simple generic interface:

    public interface IDiagnosticContextHandler
    {
        void Set(string name, string value);
    }
    

    then implemented a Log4Net specific version:

    public class Log4NetDiagnosticContextHandler : IDiagnosticContextHandler
    {
        private readonly Assembly assembly;
    
        private readonly Type mdcType;
    
        public Log4NetDiagnosticContextHandler()
        {
            this.assembly = Assembly.Load("log4net");
            this.mdcType = this.assembly.GetType("log4net.MDC", true);
        }
    
        public void Set(string name, string value)
        {
            this.mdcType.InvokeMember("Set", BindingFlags.InvokeMethod, null, null, new object[] { name, value });
        }
    }
    

    I then used an IoC container (Spring.Net) to bring in the correct implementation. If a different logging framework was later required it'd be a simple matter of writing a different implementation of that interface changing the IoC configuration.