Skip to content

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

Description

@dglynch

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");
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions