有什么方法可以只记录异常的简单名称,而无需从代码中显式检索它?
例如,通过调用
log.error(exception);
具有登录模式
%d{yyyy-MM-dd}|%-5level|%m%n
而不是仅记录异常堆栈跟踪
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)
预计将记录一个单独的具有异常简单名称的列
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)
解决方法:
您可以编写自己的custom conversion specifier.
为此,您可以在logback.xml中为%exname符号声明一个转换规则,如下所示:
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<conversionRule conversionWord="exname" converterClass="com.foo.ExceptionNameConverter" />
...
</configuration>
然后像这样声明ExceptionNameConverter:
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();
}
}
现在,使用此模式:
%d{yyyy-MM-dd}|%-5level|%exname|%m%n
以下日志语句:
logger.error("Boom!", new RuntimeException("ouch"));
将发出:
2018-09-26|ERROR|java.lang.RuntimeException|Boom!