Java KeyValuePairConverter-class And Method Code Example


The KeyValuePairConverter class is a part of the Logback library, specifically the logback-classic module. It is a Converter implementation that can be used to add key-value pairs to log messages. Here is an example of how you might use it in a Logback configuration file:

<configuration>
  <conversionRule conversionWord="kvp" converterClass="ch.qos.logback.classic.pattern.KeyValuePairConverter" />

  <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %kvp{mykey} - %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} - %kvp{mykey} - %msg%n". The %kvp{mykey} part of the pattern is where the key-value pair is inserted into the log message. In this example, the key is mykey and the value can be set in the code when logging is done, for example

Logger logger = LoggerFactory.getLogger(MyClass.class);
logger.setProperty("mykey","myvalue");
logger.info("Hello World!");

It will log "11:12:23.456 [main] INFO com.example.MyClass - mykey=myvalue - Hello World!"

You can also add key-value pairs to the MDC (mapped diagnostic context) which 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 MDC to add a key-value pair to all log messages for a specific thread:

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

It will log "11:12:23.456 [main] INFO com.example.MyClass - mykey=myvalue - Hello World!"

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