slf4j icon indicating copy to clipboard operation
slf4j copied to clipboard

How are MDC.pushByKey() and related methods supposed to work?

Open dglynch opened this issue 4 months ago • 2 comments

There are three related methods in the MDC class:

  • pushByKey()
  • popByKey()
  • getCopyOfDequeByKey()

Similarly, there are four related methods in the MDCAdapter interface:

  • pushByKey()
  • popByKey()
  • getCopyOfDequeByKey()
  • clearDequeByKey()

I say these methods are "related" because, in all the implementations of the MDCAdapter interface I can find, these four methods have zero coupling with the other methods of the class. Pushing or popping does not call put() or remove(), or otherwise affect the contents of the threadlocal map field(s), nor the return value of get(). Instead, these three or four methods just interact with their own dedicated field. Crucially, calling them has no impact on logging.

Specifically, these are the implementations which have this design:

  • org.slf4j.helpers.BasicMDCAdapter
  • org.slf4j.reload4j.Reload4jMDCAdapter
  • ch.qos.logback.classic.util.LogbackMDCAdapter
  • ch.qos.logback.classic.util.LogbackMDCAdapterSimple

There are some method header JavaDoc comments in the MDC class, but they don't really explain how these methods are supposed to be used, nor why they are even part of this class.

Since these methods don't interact with put() or get(), it seems like the caller is supposed to do that itself. Is that correct? For example, is the caller always supposed to do something like this?

try {
  MDC.pushByKey("foo", MDC.get("foo"));
  MDC.put("foo", "bar");
  // business code
} finally {
  MDC.put("foo", MDC.popByKey("foo"));
}

If this is the expected way to use these methods, why does the following alternative code appear as an example in issue #461? Doesn't this code do nothing at all?

try {
  MDC.pushByKey("foo", "bar");
  // business code
} finally {
  MDC.popByKey("foo");
}

dglynch avatar Nov 24 '25 16:11 dglynch