2011-04-13 47 views
5

在我的自定義異常類,我重寫toString()覆蓋的logback錯誤輸出

@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有)

然而,當我登錄此類異常(通過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。

回答

3

一個快速和骯髒的方式是這樣的: logger.warn( 「your_message_here \ n {}」,err.toString());

一個更好的辦法是寫自己的自定義轉換符(見logback manual以便自定義錯誤處理您的應用程序代碼中抽象出來,並可以配置它是通過在你的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停止平時的異常處理

+2

您應該ThrowableHandlingConverter擴展(而不是從ClassicConverter延伸)。那麼你也不需要%nopex黑客。而且,如果你想打印堆棧跟蹤,%myCon應該在%n之後。 – 2016-07-06 14:10:09