[logback-user] MDC scopes on Spring Boot applications

Yih Tsern sim_yihtsern at yahoo.com
Wed Jul 27 19:04:48 CEST 2022


Personally, I avoid `MDC.clear()` (unless there is a REALLY good reason to do so), and only mostly use `MDC.remove(...)`.

And I usually practise "a class (or group of closely related classes eg have a separate before & after interceptor classes) should only ever remove what they have previously added - should not remove what other unrelated classes added (unless there is a REALLY good reason)".
________________________________
From: logback-user <logback-user-bounces at qos.ch> on behalf of Zac Harvey <bitbythecron at gmail.com>
Sent: Thursday, July 28, 2022 12:57:23 AM
To: logback users list <logback-user at qos.ch>
Subject: [logback-user] MDC scopes on Spring Boot applications


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<http://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/7dd9517a/attachment-0001.html>


More information about the logback-user mailing list