I'm interested in utilizing the Mapped Diagnostic Context (MDC) but have two types of MDC needs:

I know that MDC is thread-safe, so I'm guessing each HTTP request will have its own "blank slate" version/instance of the MDC to work with, which takes care of my request-scoped needs. But from inside request handlers (servlet filters, Spring controllers, etc.) I still need the global MDC key-value pairs present in any log messages that are made.

For example, say, at server startup I need to add:

MDC.put("Server-Instance-Id", serverInstanceId);

I will need "Server-Instance-Id" in every single log message sent, regardless of what thread/request the log message is sent from.

But then say in my FizzController#getFizzes() method, which accepts HTTP requests to, say, GET /v1/fizzes, I have:

MDC.put("Fruit", pear.getName());
logger.info("User is requested all fizzes");

In this case above, I would want both "Server-Instance-Id" and "Fruit" values included in the log message.

Similarly, if I clear the MDC (MDC.clear()) from inside a request thread (such as a call to FizzController#getFizzes()), I don't want it to clear the global context variables (such as "Server-Instance-Id"). Only clear the request-scoped ones.

Does anyone know how to accomplish this with SLF4J config or its API?