javaslf4jlogback-classic

How do I supply my own MDCAdapter to slf4j?


I am using slf4j and logback to provide logging services to my set of microservices.

I want to ensure that any entries that I add to the MDC always have lower case names, so I'm investigating substituting the LogBackMDCAdapter class with a similar implementation that just forces the key name to be lowercase.

Is this a sensible approach? If it is, how do I get my MDC adapter to be used in preference to the Logback version?


Solution

  • Here's the solution I ended up using.

    Create a class called org.slf4j.impl.StaticMDCBinder inside your project. This can be a copy of the org.slf4j.impl.StaticMDCBinder that ships with slf4j.

    Alter that class to return your own instance of MDCAdapter. As I knew that I would be using Logback as the underlying logging system, I just subclassed ch.qos.logback.classic.util.LogbackMDCAdapter and overrode the put method to force the key in to lowercase.

    The binder :

    public class StaticMDCBinder {
       public static final StaticMDCBinder SINGLETON = new StaticMDCBinder();
    
       private StaticMDCBinder() {
       }
    
       public MDCAdapter getMDCA() {
          return new DavesMDCAdapter();
       }
    
       public String getMDCAdapterClassStr() {
           return DavesMDCAdapter.class.getName();
       }
    }
    

    And the MDC Adapter

    public class DavesMDCAdapter extends LogbackMDCAdapter {
    
    public void put(String key, String val) throws IllegalArgumentException{
        super.put(key.toLowerCase(),val);
    }