qos-ch / slf4j

Simple Logging Facade for Java
http://www.slf4j.org
MIT License
2.32k stars 980 forks source link

putCloseable should not remove the key from MDC if it was previously set to a different value #404

Open mdpearson opened 5 months ago

mdpearson commented 5 months ago

Our team wrote some code that broadly looked like this:

MDC.put("color", "red");

try(ignored = MDC.putCloseable("color", "green")) {
...
}

assertTrue(MDC.get("color", "green")) // fails, the key is deleted

It should be an easy patch to allow callers to nest putCloseable calls and get expected results; in fact, I'll go try to write one now.

Thank you very much, by the way, for SLF4j -- it's a wonderful tool. Cheers

huxi commented 1 month ago

We had the same issue and addressed it by writing our own NestedMDCClosable, essentially wrapping the MDC.

This should also be taken into account for the MDCAmbit proposal in #377 and #372.

Our use case are correlationIds in Services where a UUID is supposed to turn up in every log statement of a method call.

This works perfectly in case of a single service but breaks with the current MDCClosable implementation once one such service is directly calling another such service or methods of itself.