0

我写了一个基于 log4j 的 Log4j Custom Appender ConsoleAppender

我正在根据我得到的异常堆栈跟踪构造一个字符串,我面临的问题是我在其中看到字符 '\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;
    }

}
4

1 回答 1

0

我非常怀疑换行符来自除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也不会。

您的类使用什么 Layout 实现进行初始化?该布局的format()方法是如何实现的?希望您的 IDE 支持条件断点,并且您可以在追加后停止调试器 ifstringBuffer.toString().contains("\n");

于 2013-06-28T10:49:25.333 回答