Java ThrowableProxyConverter-class And Method Code Example


The ThrowableProxyConverter class is a part of the Logback library that can be used to include information about an exception that was thrown and caught in a log message.

Here is an example of how you might use the ThrowableProxyConverter in a Logback configuration file:

<configuration>
  <conversionRule conversionWord="exception" converterClass="ch.qos.logback.classic.pattern.ThrowableProxyConverter"/>

  <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n%exception</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} - %msg%n%exception". The %exception part of the pattern is where the information about the exception that was thrown and caught is inserted into the log message. If no exception was caught, the %exception part of the pattern will be blank.

The example assumes that the logging calls are made inside the catch block of a try-catch statement, to log the exception details. In the example log format, the exception detail would be printed on a new line after the message

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.