Java MarkerConverter-class And Method Code Example


The MarkerConverter class is a part of the Logback library that can be used to include information about the marker associated with a log event in the log message. A marker is a simple object that can be used to add additional information to log events. Here is an example of how you might use the MarkerConverter in a Logback configuration file:

<configuration>
  <conversionRule conversionWord="marker" converterClass="ch.qos.logback.classic.pattern.MarkerConverter" />

  <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %marker - %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} - %marker - %msg%n". The %marker part of the pattern is where the information about the marker associated with the log event is inserted into the log message.

To add a marker to a log event, you can use the MarkerFactory.getMarker(String name) method to obtain a marker with a specific name and then associate it with the log event using the LoggingEvent.setMarker(Marker marker) method. Here's an example:

Marker marker = MarkerFactory.getMarker("MY_MARKER");
logger.info(marker, "Hello World!");

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

You can also create child markers and add them to the parent marker for more granular log filtering and searching.

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.