[logback-user] MDC scopes on Spring Boot applications

Zac Harvey bitbythecron at gmail.com
Wed Jul 27 18:57:23 CEST 2022


I'm interested in utilizing the Mapped Diagnostic Context (MDC)
<https://logback.qos.ch/manual/mdc.html> but have two types of MDC needs:

   - *global*: I need to add certain key-value pairs to the MDC when the
   server starts up, and I need them present in every log message for the
   entire life of the server; and
   - *request-scoped* (thread scoped?): certain key-value pairs need to be
   added to the MDC but will change for every/most HTTP request the server
   receives

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?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mailman.qos.ch/pipermail/logback-user/attachments/20220727/dcad198b/attachment.html>


More information about the logback-user mailing list