Java CallerDataConverter-class And Method Code Example

The CallerDataConverter class is a Converter implementation for logback that can be used to add the class and method name of the calling method to the log message. This can be useful for identifying the location of log events in your code.

Here's an example of how you could use the CallerDataConverter class in a logback configuration file:

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

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

    <conversionRule conversionWord="xEx" converterClass="ch.qos.logback.classic.pattern.CallerDataConverter" />

In this example, we first create a Console Appender, and then we set the encoder pattern to include %xEx.

The %xEx Conversion word tells the encoder to use the CallerDataConverter to add the calling class and method name to the log message.

Then we set the logging level to debug to print all the messages that are of debug level or above,

Then we have created a conversionRule which maps the xEx to the CallerDataConverter class, so that the CallerDataConverter is used when the xEx conversion word is encountered in the pattern.

You need to add logback classic library in the classpath to use this example.

Now when you log any message, it will have the class and method name of the calling method in the message, making it easy to identify the location of log events in the code.