Search code examples
javaspringlogginglogbackslf4j

Logback - How to log the simple name of an exception separately


Is there any way you can log only the simple name of an exception without explicitly retrieving it from the code?

For example, by calling

log.error(exception);

with a logback pattern

%d{yyyy-MM-dd}|%-5level|%m%n

instead of just logging the exception stack traces

2018-01-01|ERROR|
mainPackage.foo.bar.RocketExplosionException: Houston we have a problem
  at mainPackage.foo.bar.TestThrower.fire(TestThrower.java:22)
  at mainPackage.foo.bar.TestThrower.readyToLaunch(TestThrower.java:17)
  at mainPackage.ExceptionLauncher.main(ExceptionLauncher.java:38)

A separate column with the simple name of the exception is expected to be logged

2018-01-01|ERROR|RocketExplosionException|
mainPackage.foo.bar.RocketExplosionException: Houston we have a problem
  at mainPackage.foo.bar.TestThrower.fire(TestThrower.java:22)
  at mainPackage.foo.bar.TestThrower.readyToLaunch(TestThrower.java:17)
  at mainPackage.ExceptionLauncher.main(ExceptionLauncher.java:38)

Solution

  • You could write your own custom conversion specifier.

    To do this, you would declare a conversion rule in your logback.xml for the %exname symbolic like so:

    <?xml version="1.0" encoding="UTF-8" ?>
    <configuration>
        <conversionRule conversionWord="exname" converterClass="com.foo.ExceptionNameConverter" />
    
        ...
    
    </configuration>
    

    Then declare ExceptionNameConverter like so:

    import ch.qos.logback.classic.pattern.ThrowableProxyConverter;
    import ch.qos.logback.classic.spi.IThrowableProxy;
    
    public class ExceptionNameConverter extends ThrowableProxyConverter {
        @Override
        protected String throwableProxyToString(IThrowableProxy tp) {
            return tp.getClassName();
        }
    }
    

    Now, using this pattern:

    %d{yyyy-MM-dd}|%-5level|%exname|%m%n
    

    The following log statement:

    logger.error("Boom!", new RuntimeException("ouch"));
    

    Will emit:

    2018-09-26|ERROR|java.lang.RuntimeException|Boom!