在我的自定义异常类中,我已经重写了toString()
:
@Override
public String toString() {
final String msg = getLocalizedMessage();
// base
String str = getClass().getName() + ": [" + code + "]";
// message
if (msg != null)
str += " " + msg;
// extra
if (extra != null) {
str += '\n' + extra.toString();
}
return str;
}
(是的,我知道我应该使用StringBuilder
there)
但是,当我记录这样的异常时(通过org.slf4j.Logger.warn(String msg, Throwable err)
)输出与普通异常相同:
webersg.util.service.ServiceError: null
at webersg.util.service.ServiceTools.decodeException(ServiceTools.java:39) ~[bin/:na]
at tr.silvercar.rummikub.robot.LobbyConnection.sendRequestTo(LobbyConnection.java:143) ~[bin/:na]
at tr.silvercar.rummikub.robot.LobbyConnection.sendRequest(LobbyConnection.java:98) ~[bin/:na]
at tr.silvercar.rummikub.robot.Robot.<init>(Robot.java:32) ~[bin/:na]
at tr.silvercar.rummikub.robot.RobotController.start(RobotController.java:81) ~[bin/:na]
at tr.silvercar.rummikub.robot.runners.LocalAltinRobot.main(LocalSilverRobot.java:132) [bin/:na]
我怎样才能显示我的额外数据?我的日志实现是Logback。
一种快速而肮脏的方法是这样的:
logger.warn("your_message_here \n{}", err.toString());
更好的方法是编写您自己的自定义转换说明符(请参阅回溯手册 http://logback.qos.ch/manual/layouts.html以便从应用程序代码中抽象出自定义错误处理,并且您可以通过 logback.xml 中的自定义转换字来配置它的使用。
这是一个简单的示例,可以完成您想要的操作:
package com.example.logging;
import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.classic.spi.ThrowableProxy;
/**
* Simple exception converter.
*
*/
public class MyExceptionConverter extends ClassicConverter {
/* (non-Javadoc)
* @see ch.qos.logback.core.pattern.Converter#convert(java.lang.Object)
*/
@Override
public String convert(ILoggingEvent event) {
IThrowableProxy itp = event.getThrowableProxy();
if (itp instanceof ThrowableProxy) {
ThrowableProxy tp = (ThrowableProxy)itp;
return tp.getThrowable().toString();
}
return "";
}
}
然后在 logback.xml 中,您需要像这样引用它:
<conversionRule conversionWord="myCon"
converterClass="com.example.logging.MyExceptionConverter" />
然后在编码器模式中使用 %myCon ,如下所示:
<encoder>
<pattern>%d{dd MMM yyyy HH:mm:ss.SSS} %logger{0}: %myCon %nopex%n</pattern>
</encoder>
请注意,添加 %nopex 会停止通常的异常处理
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)