1

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?

DaveH
  • 7,187
  • 5
  • 32
  • 53
  • Just create wrapper which convert property name. – talex May 13 '19 at 10:09
  • Thanks @talex - but that won't stop a developer calling `MDC.put("KEY","value")` directly, which I am trying to guard against – DaveH May 13 '19 at 10:12
  • Is there a reason you have to do it? Forcing lowercase key seems like a strange problem to solve. – Karol Dowbecki May 13 '19 at 10:19
  • I want to add a message id to the MDC and then propogate that message id to any other microservice that gets called. I'm passing them as request headers in the case of an HTTP call, and the servlet container that I am running in always forces the request header names in to lowercase. So if I add a value to the MDC of `messageId`, it gets translated to `messageid` by the time it gets in to my downstream microservice. – DaveH May 13 '19 at 10:45
  • Make sure to also remove `_` character as sometimes it doesn't work https://stackoverflow.com/questions/22856136/why-underscores-are-forbidden-in-http-header-names – Karol Dowbecki May 13 '19 at 10:47

1 Answers1

0

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);
}
DaveH
  • 7,187
  • 5
  • 32
  • 53