Java MDCConverter-class And Method Code Example


The MDCConverter class is another part of the Logback library that can be used to add information from the Mapped Diagnostic Context (MDC) to log messages. The MDC is a map that is stored as a thread-local variable and can be used to store information that should be included in all log messages for a specific thread. Here is an example of how you might use the MDCConverter in a Logback configuration file:

<configuration>
  <conversionRule conversionWord="mdc" converterClass="ch.qos.logback.classic.pattern.MDCConverter" />

  <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %mdc - %msg%n</pattern>
    </encoder>
  </appender>

  <root level="debug">
    <appender-ref ref="CONSOLE" />
  </root>
</configuration>

This configuration file sets up a CONSOLE appender that outputs log messages in the format "%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %mdc - %msg%n". The %mdc part of the pattern is where the values from the MDC are inserted into the log message. To add a key-value pair to the MDC, you can use the MDC.put(String key, String value) method, like so:

MDC.put("mykey", "myvalue");
logger.info("Hello World!");

This will output log message in the format of "2022-12-10 13:54:23.456 [main] INFO com.example.MyClass - mykey=myvalue - Hello World!"

You can also remove an entry from the MDC using the MDC.remove(String key) method.

Please note that, the output will be written to the console in this example, you can use file based appender to output the logs to a file. And you can refer to the logback documentation for more information and options available.