Кейс использования Mapping Diagnostic Context и @Async
Речь в этой небольшой заметке пойдёт про то, как с пользой можно использовать MDC в Spring-проекте. Поводом написать статью послужила другая недавняя статья на Хабре.

Мы — небольшая команда backend-разработчиков, включая меня — работаем над проектом сервера для мобильных приложений для некой организации. Приложениями пользуются только её сотрудники и значительного highload-а у нас нет. Поэтому для сервера мы выбрали максимально привычный нам стек: Java и Spring Boot на servlet-контейнерах.
Здесь я хотел бы рассказать про свой подход к логированию бизнес-процессов при помощи MDC . Почему именно MDC? Фактически, имеется несколько реплик приложения, которые развёрнуты в Kubernetes, и все логи стекаются в единый агрегатор (Graylog). В конфигурации logback-а добавлен специальный appender, который отправляет все логи по нужному адресу, а также к каждому сообщению добавляет все имеющиеся в MDC поля:
$ $ 1.1 true true true environment=$,microservice=$ environment=String,microservice=String yyyy-MM-dd HH:mm:ss,SSS 8192
Это очень удобно — можно отправить название окружения (боевое или одно из тестовых), название конкретного микросервиса, Spring Cloud Sleuth добавляет в него данные трассировки (traceId и spanId), а мне захотелось отправлять туда такие поля, которые в последствии помогут искать в Graylog-е причины каких-то сбоев именно мне. Если на вашем проекте используется стек ELK, то скорее всего там всё аналогично, просто мне с ним сталкиваться не приходилось.
Подавляющая часть входящих запросов проходит через кастомный Security-фильтр, который по заголовкам запроса определяет пользователя. Именно в этот момент удобно подложить в MDC то, что хочется. Сперва описываем класс с теми полями, которые хочется подложить:
@UtilityClass public class MdcKeys < /** * Значение HTTP-заголовка User-Agent из внешнего запроса. */ public final String MDC_USER_AGENT = "user-agent"; /** * Значение заголовка Authorization из внешнего запроса. */ public final String MDC_USER_TOKEN = "authorization"; /** * Логин пользователя, от имени которого поступил запрос. */ public final String MDC_USER_LOGIN = "login"; /** * URL, на который поступил внешний запрос. */ public final String MDC_API_URL = "apiUrl"; // . и некоторые другие . >
Если просто устанавливать значения через MDC#put то они не будут удаляться из него после обработки запроса, что чревато проблемами: не все запросы должны быть авторизованы, поэтому часть проскакивает мимо вызова AuthenticationManager-а. Так как потоки, которые обрабатывают запросы, живут в servlet-контейнере и не пересоздаются, старые значения «замусоривают» нам картину. Выход простой — обернуть в try-catch и почистить за собой в блоке finally.
Далее возникает вопрос о том, что делать с методами, помеченными аннотацией @Async . Методы, помеченные ей, выполняются на отдельном пуле потоков, а так как значения в MDC локальны по отношению к текущему потоку, нужно их как-то туда скопировать и в конце метода не забыть удалить. Решение подсмотрено опять же у Spring Security. Находим место в конфигурации, где у нас создаётся пул потоков:
/** * TaskExecutor, используемый для запуска асинхронных методов. */ @Bean @Qualifier("taskExecutor") TaskExecutor taskExecutor() < ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); // . код настройки taskExecutor-а опущен . taskExecutor.setTaskDecorator(new AsyncTaskCustomDecorator()); return taskExecutor; >
И устанавливаем декоратор, который будет оборачивать все запускаемые асинхронные методы своим кодом:
private static class AsyncTaskCustomDecorator implements TaskDecorator < @Override @NonNull public Runnable decorate(@NonNull Runnable runnable) < var runnableWithRestoredMDC = LoggingUtils.decorateMdcCopying(runnable); return new DelegatingSecurityContextRunnable(runnableWithRestoredMDC); >>
Фактически, оборачивание происходит дважды: один раз нашим кодом (LoggingUtils#decorateMdcCopying) и один раз для самой Spring Security (иначе мы сломаем передачу контекста в SecurityContextHolder-е). Можно было бы «сделать всю работу» на месте, но мы вынесли код в утильный класс. Смотрим дальше:
@UtilityClass public class LoggingUtils < private final SetCOPYABLE_MDC_FIELDS = Set.of( MdcKeys.MDC_USER_AGENT, MdcKeys.MDC_USER_TOKEN, MdcKeys.MDC_USER_LOGIN, MdcKeys.MDC_API_URL, MdcKeys.MDC_MOBILE_FEATURE); /** * Декорирует Runnable таким образом, что при его вызове в другом потоке * будут восстановлены значения нескольких определённых полей MDC из * текущего потока. */ public Runnable decorateMdcCopying(Runnable runnable) < // Получаем значения, которые нужно будет восстановить в MDC. MapmdcMap = getMdcMeaningfulMap(); return () -> < // Восстанавливаем в значения полей MDC из потока-создателя. try (var ignored = mdcCloseable(mdcMap)) < // Вызываем оригинальный код. runnable.run(); >>; > private Map getMdcMeaningfulMap() < return StreamEx.of(COPYABLE_MDC_FIELDS) .mapToEntry(MDC::get) .nonNullValues() .toMap(); >public MdcCloseable mdcCloseable(Map values) < // Если нечего устанавливать, вернём ничего не закрывающий singleton. if (MapUtils.isEmpty(values)) < return MdcCloseable.EMPTY; >// Вариант, когда нам не нужно будет ничего восстанавливать в MDC. var mdcMap = MapUtils.emptyIfNull(MDC.getCopyOfContextMap()); if (MapUtils.isEmpty(mdcMap)) < return new MdcCloseable(values, Collections.emptyMap()); >// Значения, которые нужно будет вернуть в MDC // (если они там были до нас). Map original = EntryStream.of(mdcMap) .nonNullValues() .filterKeys(values::containsKey) .filterKeyValue((k, v) -> Objects.equals(v, mdcMap.get(k))) .toMap(); return new MdcCloseable(values, original); > public MdcCloseable mdcCloseable(String key, String value) < return mdcCloseable(Map.of(key, value)); >>
И, да, мы написали собственную альтернативу MDC.MDCCloseable:
Данный класс можно использовать отдельно в коде приложения для установки каких-то дополнительных полей, которые помогут в дальнейшем искать логи в агрегаторе, например:
// . какой-то код . try (var ignored = LoggingUtils.mdcCloseable(MdcKeys.SOME_EXT_SVC_URL, url) < /* Все логи в агрегаторе из этого блока кода будут содержать ключ MdcKeys.SOME_EXT_SVC_URL и значение url. */ >// . какой-то код .
Всё вышеописанное может оказаться дичайшим over-engineering-ом.
Я не очень близко знаком с Reactor и WebFlux, поэтому мне кажется, что применить с ними аналогичный подход будет немного сложнее.
Lombok; var , Map.of , Set.of и другие фичи новых версий Java; StreamEx — это всё огонь.
Не бейте строго за первую статью на ресурсе.
Chapter 8: Mapped Diagnostic Context
One of the design goals of logback is to audit and debug complex distributed applications. Most real-world distributed systems need to deal with multiple clients simultaneously. In a typical multithreaded implementation of such a system, different threads will handle different clients. A possible but slightly discouraged approach to differentiate the logging output of one client from another consists of instantiating a new and separate logger for each client. This technique promotes the proliferation of loggers and may increase their management overhead.
A lighter technique consists of uniquely stamping each log request servicing a given client. Neil Harrison described this method in the book Patterns for Logging Diagnostic Messages in Pattern Languages of Program Design 3, edited by R. Martin, D. Riehle, and F. Buschmann (Addison-Wesley, 1997). Logback leverages a variant of this technique included in the SLF4J API: Mapped Diagnostic Contexts (MDC).
package org.slf4j; public class MDC < //Put a context value as identified by key //into the current thread's context map. public static void put(String key, String val); //Get the context identified by thekeyparameter. public static String get(String key); //Remove the context identified by thekeyparameter. public static void remove(String key); //Clear all entries in the MDC. public static void clear(); >
The MDC class contains only static methods. It lets the developer place information in a diagnostic context that can be subsequently retrieved by certain logback components. The MDC manages contextual information on a per thread basis. Typically, while starting to service a new client request, the developer will insert pertinent contextual information, such as the client id, client’s IP address, request parameters etc. into the MDC . Logback components, if appropriately configured, will automatically include this information in each log entry.
Please note that MDC as implemented by logback-classic assumes that values are placed into the MDC with moderate frequency. Also note that a child thread does not automatically inherit a copy of the mapped diagnostic context of its parent.
The next application named SimpleMDC demonstrates this basic principle.
package chapters.mdc; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import ch.qos.logback.classic.PatternLayout; import ch.qos.logback.core.ConsoleAppender; public class SimpleMDC < static public void main(String[] args) throws Exception < // You can put values in the MDC at any time. Before anything else // we put the first name MDC.put("first", "Dorothy"); [ SNIP ] Logger logger = LoggerFactory.getLogger(SimpleMDC.class); // We now put the last name MDC.put("last", "Parker"); // The most beautiful two words in the English language according // to Dorothy Parker: logger.info("Check enclosed."); logger.debug("The most beautiful two words in English."); MDC.put("first", "Richard"); MDC.put("last", "Nixon"); logger.info("I am not a crook."); logger.info("Attributed to the former US president. 17 Nov 1973."); >[ SNIP ] >
The main method starts by associating the value Dorothy with the key first in the MDC . You can place as many value/key associations in the MDC as you wish. Multiple insertions with the same key will overwrite older values. The code then proceeds to configure logback.
%X %X - %m%n
Note the usage of the %X specifier within the PatternLayout conversion pattern. The %X conversion specifier is employed twice, once for the key named first and once for the key named last. After obtaining a logger corresponding to SimpleMDC.class , the code associates the value Parker with the key named last. It then invokes the logger twice with different messages. The code finishes by setting the MDC to different values and issuing several logging requests. Running SimpleMDC yields:
Dorothy Parker - Check enclosed. Dorothy Parker - The most beautiful two words in English. Richard Nixon - I am not a crook. Richard Nixon - Attributed to the former US president. 17 Nov 1973.
The SimpleMDC application illustrates how logback layouts, if configured appropriately, can automatically output MDC information. Moreover, the information placed into the MDC can be used by multiple logger invocations.
Advanced Use
Mapped Diagnostic Contexts shine brightest within client server architectures. Typically, multiple clients will be served by multiple threads on the server. Although the methods in the MDC class are static, the diagnostic context is managed on a per-thread basis, allowing each server thread to bear a distinct MDC stamp. MDC operations such as put() and get() affect only the MDC of the current thread, and the children of the current thread. The MDC in other threads remain unaffected. Given that MDC information is managed on a per-thread basis, each thread will have its own copy of the MDC . Thus, there is no need for the developer to worry about thread-safety or synchronization when programming with the MDC because it handles these issues safely and transparently.
The next example is somewhat more advanced. It shows how the MDC can be used in a client-server setting. The server-side implements the NumberCruncher interface shown in Example 7.2 below. The NumberCruncher interface contains a single method named factor() . Using RMI technology, the client invokes the factor() method of the server application to retrieve the distinct factors of an integer.
package chapters.mdc; import java.rmi.Remote; import java.rmi.RemoteException; /** * NumberCruncher factors positive integers. */ public interface NumberCruncher extends Remote < /** * Factor a positive integer number and return its * distinct factor's as an integer array. * */ int[] factor(int number) throws RemoteException; >
The NumberCruncherServer application, listed in Example 7.3 below, implements the NumberCruncher interface. Its main method exports an RMI Registry on the local host that accepts requests on a well-known port.
package chapters.mdc; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import java.util.Vector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.core.joran.spi.JoranException; /** * A simple NumberCruncher implementation that logs its progress when * factoring numbers. The purpose of the whole exercise is to show the * use of mapped diagnostic contexts in order to distinguish the log * output from different client requests. * */ public class NumberCruncherServer extends UnicastRemoteObject implements NumberCruncher < private static final long serialVersionUID = 1L; static Logger logger = LoggerFactory.getLogger(NumberCruncherServer.class); public NumberCruncherServer() throws RemoteException < >public int[] factor(int number) throws RemoteException < // The client's host is an important source of information. try < MDC.put("client", NumberCruncherServer.getClientHost()); > catch (java.rmi.server.ServerNotActiveException e) < logger.warn("Caught unexpected ServerNotActiveException.", e); >// The information contained within the request is another source // of distinctive information. It might reveal the users name, // date of request, request ID etc. In servlet type environments, // useful information is contained in the HttpRequest or in the // HttpSession. MDC.put("number", String.valueOf(number)); logger.info("Beginning to factor."); if (number else if (number == 1) < return new int[] < 1 >; > Vector factors = new Vector(); int n = number; for (int i = 2; (i while ((n % i) == 0); > // Placing artificial delays in tight loops will also lead to // sub-optimal results. :-) delay(100); > if (n != 1) < logger.info("Found factor " + n); factors.addElement(new Integer(n)); >int len = factors.size(); int[] result = new int[len]; for (int i = 0; i < len; i++) < result[i] = ((Integer) factors.elementAt(i)).intValue(); >// clean up MDC.remove("client"); MDC.remove("number"); return result; > static void usage(String msg) < System.err.println(msg); System.err.println("Usage: java chapters.mdc.NumberCruncherServer configFile\n" + " where configFile is a logback configuration file."); System.exit(1); >public static void delay(int millis) < try < Thread.sleep(millis); >catch (InterruptedException e) < >> public static void main(String[] args) < if (args.length != 1) < usage("Wrong number of arguments."); >String configFile = args[0]; if (configFile.endsWith(".xml")) < try < LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc); lc.reset(); configurator.doConfigure(args[0]); >catch (JoranException je) < je.printStackTrace(); >> NumberCruncherServer ncs; try < ncs = new NumberCruncherServer(); logger.info("Creating registry."); Registry registry = LocateRegistry.createRegistry(Registry.REGISTRY_PORT); registry.rebind("Factor", ncs); logger.info("NumberCruncherServer bound and ready."); >catch (Exception e) < logger.error("Could not bind NumberCruncherServer.", e); return; >> >
The implementation of the factor(int number) method is of particular relevance. It starts by putting the client’s hostname into the MDC under the key client. The number to factor, as requested by the client, is put into the MDC under the key number. After computing the distinct factors of the integer parameter, the result is returned to the client. Before returning the result however, the values for the client and number are cleared by calling the MDC.remove() method. Normally, a put() operation should be balanced by the corresponding remove() operation. Otherwise, the MDC will contain stale values for certain keys. We would recommend that whenever possible, remove() operations be performed within finally blocks, ensuring their invocation regardless of the execution path of the code.
After these theoretical explanations, we are ready to run the number cruncher example. Start the server with the following command:
java chapters.mdc.NumberCruncherServer src/main/java/chapters/mdc/mdc1.xml
The mdc1.xml configuration file is listed below:
Example 7.4: Configuration file (logback-examples/src/main/java/chapters/mdc/mdc1.xml)
%-4r [%thread] %-5level C:%X N:%X - %msg%n
Note the use of the %X conversion specifier within the Pattern option.
The following command starts an instance of NumberCruncherClient application:
java chapters.mdc.NumberCruncherClient hostname
where hostname is the host where the NumberCruncherServer is running
Executing multiple instances of the client and requesting the server to factor the numbers 129 from the first client and shortly thereafter the number 71 from the second client, the server outputs the following:
70984 [RMI TCP Connection(4)-192.168.1.6] INFO C:orion N:129 - Beginning to factor. 70984 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 2 as a factor. 71093 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 3 as a factor. 71093 [RMI TCP Connection(4)-192.168.1.6] INFO C:orion N:129 - Found factor 3 71187 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 4 as a factor. 71297 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 5 as a factor. 71390 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 6 as a factor. 71453 [RMI TCP Connection(5)-192.168.1.6] INFO C:orion N:71 - Beginning to factor. 71453 [RMI TCP Connection(5)-192.168.1.6] DEBUG C:orion N:71 - Trying 2 as a factor. 71484 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 7 as a factor. 71547 [RMI TCP Connection(5)-192.168.1.6] DEBUG C:orion N:71 - Trying 3 as a factor. 71593 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 8 as a factor. 71656 [RMI TCP Connection(5)-192.168.1.6] DEBUG C:orion N:71 - Trying 4 as a factor. 71687 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 9 as a factor. 71750 [RMI TCP Connection(5)-192.168.1.6] DEBUG C:orion N:71 - Trying 5 as a factor. 71797 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 10 as a factor. 71859 [RMI TCP Connection(5)-192.168.1.6] DEBUG C:orion N:71 - Trying 6 as a factor. 71890 [RMI TCP Connection(4)-192.168.1.6] DEBUG C:orion N:129 - Trying 11 as a factor. 71953 [RMI TCP Connection(5)-192.168.1.6] DEBUG C:orion N:71 - Trying 7 as a factor. 72000 [RMI TCP Connection(4)-192.168.1.6] INFO C:orion N:129 - Found factor 43 72062 [RMI TCP Connection(5)-192.168.1.6] DEBUG C:orion N:71 - Trying 8 as a factor. 72156 [RMI TCP Connection(5)-192.168.1.6] INFO C:orion N:71 - Found factor 71
The clients were run from a machine called orion as can be seen in the above output. Even if the server processes the requests of clients near-simultaneously in separate threads, the logging output pertaining to each client request can be distinguished by studying the output of the MDC . Note for example the stamp associated with number, i.e. the number to factor.
The attentive reader might have observed that the thread name could also have been used to distinguish each request. The thread name can cause confusion if the server side technology recycles threads. In that case, it may be hard to determine the boundaries of each request, that is, when a given thread finishes servicing a request and when it begins servicing the next. Because the MDC is under the control of the application developer, MDC stamps do not suffer from this problem.
Automating access to the MDC
As we’ve seen, the MDC is very useful when dealing with multiple clients. In the case of a web application that manages user authentication, one simple solution could be to set the user’s name in the MDC and remove it once the user logs out. Unfortunately, it is not always possible to achieve reliable results using this technique. Since MDC manages data on a per thread basis, a server that recycles threads might lead to false information contained in the MDC .
Within the servlet filter’s doFilter method, we can retrieve the relevant user data through the request (or a cookie therein), store it the MDC . Subsequent processing by other filters and servlets will automatically benefit from the MDC data that was stored previously. Finally, when our servlet filter regains control, we have an opportunity to clean MDC data.
Here is an implementation of such a filter:
package chapters.mdc; import java.io.IOException; import java.security.Principal; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.slf4j.MDC; public class UserServletFilter implements Filter < private final String USER_KEY = "username"; public void destroy() < >public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException < boolean successfulRegistration = false; HttpServletRequest req = (HttpServletRequest) request; Principal principal = req.getUserPrincipal(); // Please note that we could have also used a cookie to // retrieve the user name if (principal != null) < String username = principal.getName(); successfulRegistration = registerUsername(username); >try < chain.doFilter(request, response); >finally < if (successfulRegistration) < MDC.remove(USER_KEY); >> > public void init(FilterConfig arg0) throws ServletException < >/** * Register the user in the MDC under USER_KEY. * * @param username * @return true id the user can be successfully registered */ private boolean registerUsername(String username) < if (username != null && username.trim().length() >0) < MDC.put(USER_KEY, username); return true; >return false; > >
When the filter’s doFilter() method is called, it first looks for a java.security.Principal object in the request. This object contains the name of the currently authenticated user. If a user information is found, it is registered in the MDC .
Once the filter chain has completed, the filter removes the user information from the MDC .
The approach we just outlined sets MDC data only for the duration of the request and only for the thread processing it. Other threads are unaffected. Furthermore, any given thread will contain correct MDC data at any point in time.
MDC And Managed Threads
A copy of the mapped diagnostic context can not always be inherited by worker threads from the initiating thread. This is the case when java.util.concurrent.Executors is used for thread management. For instance, newCachedThreadPool method creates a ThreadPoolExecutor and like other thread pooling code, it has intricate thread creation logic.
In such cases, it is recommended that MDC.getCopyOfContextMap() is invoked on the original (master) thread before submitting a task to the executor. When the task runs, as its first action, it should invoke MDC.setContextMap() to associate the stored copy of the original MDC values with the new Executor managed thread.
MDCInsertingServletFilter
| MDC key | MDC value |
|---|---|
| req.remoteHost | as returned by the getRemoteHost() method |
| req.xForwardedFor | value of the «X-Forwarded-For» header |
| req.method | as returned by getMethod() method |
| req.requestURI | as returned by getRequestURI() method |
| req.requestURL | as returned by getRequestURL() method |
| req.queryString | as returned by getQueryString() method |
| req.userAgent | value of the «User-Agent» header |
To install MDCInsertingServletFilter add the following lines to your web-application’s web.xml file
MDCInsertingServletFilter ch.qos.logback.classic.helpers.MDCInsertingServletFilter MDCInsertingServletFilter /*
If your web-app has multiple filters, make sure that MDCInsertingServletFilter is declared before other filters. For example, assuming the main processing in your web-app is done in filter ‘F’, the MDC values set by MDCInsertingServletFilter will not be seen by the code invoked by ‘F’ if MDCInsertingServletFilter comes after ‘F’.
Once the filter is installed, values corresponding to each MDC key will be output by the %X conversion word according to the key passes as first option. For example, to print the remote host followed by the request URI on one line, the date followed by the message on the next, you would set PatternLayout ‘s pattern to:
Mapped Diagnostic Context (MDC)
Mapped Diagnostic Context (MDC) is a feature in the Logback framework (which is the default logging framework for Spring Boot) that allows you to store contextual information in a logging message. The MDC is a key-value store that is propagated between logging events, so you can use it to store information such as a user ID or request ID and then include that information in every log message emitted in a single request.
Here is an example of how you could use MDC in a Spring Boot application:
- First, you’ll need to add the logback-classic dependency to your pom.xml:
ch.qos.logback
logback-classic
1.2.3
2. Next, you’ll need to configure a logger in your logback.xml configuration file to include the MDC in the log messages:
%d [%thread] %-5level %logger - %mdc - %msg%n
3. In your Spring Boot application, you can use the MDC to store contextual information. For example, you can store the user ID in the MDC in a RequestInterceptor :
@Component
public class RequestInterceptor implements HandlerInterceptor @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception String userId = request.getHeader("userId");
MDC.put("userId", userId);
return true;
>
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception MDC.remove("userId");
>
>
The purpose of the RequestInterceptor is to store the user ID in the Mapped Diagnostic Context (MDC), which is a key-value store that can be used to add contextual information to log messages.
4. Now, every log message emitted in the context of a single request will include the user ID stored in the MDC. Here’s an example log message:
14:55:55.234 [http-nio-8080-exec-2] DEBUG c.e.s.c.RequestInterceptor - - Handling request.
This is just a simple example of how you can use the MDC in a Spring Boot application. You can store any contextual information you like in the MDC and use it to provide more context in your log messages.
To actually log the user ID, you would need to add a log statement in the appropriate place in your code. For example, you could add a log statement at the beginning of a controller method:
@Controller
public class MyController private static final Logger LOGGER = LoggerFactory.getLogger(MyController.class);
@RequestMapping("/some-endpoint")
public ResponseEntity handleRequest() LOGGER.debug("Handling request from user <>", MDC.get("userId"));
// .
>
>
With the above configuration, each time the handleRequest method is called, a log message will be emitted that includes the user ID stored in the MDC.
Thanks, before you go:
- Please clap for the story and follow the author
- Please share your questions or insights in the comments section below. Let’s help each other and become better Java developers.
- Let’s connect on LinkedIn
Mdc java что это
The MDC class is similar to the NDC class except that it is based on a map instead of a stack. It provides mapped diagnostic contexts. A Mapped Diagnostic Context, or MDC in short, is an instrument for distinguishing interleaved log output from different sources. Log output is typically interleaved when a server handles multiple clients near-simultaneously.
The MDC is managed on a per thread basis. A child thread automatically inherits a copy of the mapped diagnostic context of its parent.
The MDC class requires JDK 1.2 or above. Under JDK 1.1 the MDC will always return empty values but otherwise will not affect or harm your application.
Since: 1.2 Author: Ceki Gülcü
| Method Summary | |
|---|---|
| static void | clear () Remove all values from the MDC. |
| static Object | get (String key) Get the context identified by the key parameter. |
| static Hashtable | getContext () Get the current thread’s MDC as a hashtable. |
| static void | put (String key, Object o) Put a context value (the o parameter) as identified with the key parameter into the current thread’s context map. |
| static void | remove (String key) Remove the the context identified by the key parameter. |
| Methods inherited from class java.lang.Object |
|---|
| clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Method Detail |
|---|
put
public static void put(String key, Object o)
Put a context value (the o parameter) as identified with the key parameter into the current thread’s context map.
If the current thread does not have a context map it is created as a side effect.
get
public static Object get(String key)
Get the context identified by the key parameter.
This method has no side effects.