我已根据log4j的ConsoleAppender
编写了一个Log4j Custom Appender。
我正在根据我得到的异常堆栈跟踪构建一个String,我面临的问题是我在其中看到字符'\ 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;
}
}
答案 0 :(得分: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");