Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 679
ProtossShuttle Avatar asked Oct 14 '25 23:10

ProtossShuttle


1 Answers

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!
like image 113
glytching Avatar answered Oct 17 '25 12:10

glytching



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!