2013-06-28 58 views
0

我已經根據log4j的ConsoleAppender寫了一個Log4j自定義Appender。如何在子類化過程中避免 n在一個String內部Log4j ConsoleAppender

我基於異常堆棧跟蹤我得到構建一個String,我面臨的問題是,我看到charcters「\ n」裏面

請參閱下面的字符串,我得到它具有像字符\ n

(Test.java:<sendSymbol>:40)- THE ERROR IS \norg.springframework.remoting.RemoteLookupFailureException: Lookup of RMI stub failed; nested exception is java.rmi.ConnectException: Connection refused to host: 19.9.199.155; nested exception is: \n 

這是我CustomAppender

請讓我知道爲什麼我收到\n inside my String

package com; 

import org.apache.log4j.AppenderSkeleton; 
import org.apache.log4j.Layout; 
import org.apache.log4j.spi.LoggingEvent; 
import org.apache.log4j.spi.ThrowableInformation; 

public class TestAppender extends AppenderSkeleton { 
    public TestAppender() { 



    } 
    public TestAppender(Layout layout) { 
     this.layout = layout; 
    } 
    public void append(LoggingEvent event) { 

     ThrowableInformation throwableInfo = null; 
     Throwable throwable = null; 
     Throwable cause = null; 
     StackTraceElement[] stackTrace = null; 
     String smallIndent = ""; 
     String largeIndent = " at "; 
     StringBuffer stringBuffer = new StringBuffer(); 
     stringBuffer.append(this.layout.format(event)); 
     if ((throwableInfo = event.getThrowableInformation()) != null) { 
      if ((throwable = throwableInfo.getThrowable()) != null) { 
       cause = throwable; 
       while (cause != null) { 
        stringBuffer.append(smallIndent); 
        if (cause != throwable) { 
         stringBuffer.append("Caused by: "); 
        } 
        stringBuffer.append(cause.toString()); 
        stackTrace = cause.getStackTrace(); 
        for (int i = 0; i < stackTrace.length; i++) { 
         stringBuffer.append(largeIndent + stackTrace[i]); 
        } 

        cause = cause.getCause(); 
       } 
      } 
     } 


     System.out.println(stringBuffer.toString()); 

    } 

    public boolean requiresLayout() { 
     return true; 
    } 

    public void close() { 
     if (this.closed) { 
      return; 
     } 
     this.closed = true; 
    } 

} 

回答

1

我非常懷疑換行符來自其他任何地方,但stringBuffer.append(this.layout.format(event));調用。其他四個呼叫不應添加任何新行。從你的輸出例如:

stringBuffer.append(largeIndent + stackTrace[i]); // -- is never called 
stringBuffer.append(smallIndent); // -- won't add newline 
stringBuffer.append("Caused by: "); // -- won't add newline (and not called) 
stringBuffer.append(cause.toString()); // -- shouldn't add newline 

通過「不應該」我的意思是,任何Throwable的子類可以覆蓋toString()方法,以追加在最後一個\ n,但他們一般不和org.springframework.remoting.RemoteLookupFailureException纔不是。

什麼佈局實現是否用你的類初始化?那麼如何實現該佈局的format()方法?希望你的IDE支持條件斷點,你可以在追加後停止調試器,如果stringBuffer.toString().contains("\n");

相關問題