您可以创建一个 log4j appender 来写入 StringWriter。这是我前段时间做的一个例子:
consoleWriter = new StringWriter();
WriterAppender appender = new WriterAppender(new PatternLayout("%d{ISO8601} %p - %m%n"),consoleWriter);
appender.setName("CONSOLE_APPENDER");
appender.setThreshold(org.apache.log4j.Level.ERROR);
Logger.getRootLogger().addAppender(appender);
它将所有 ERROR 日志写入 consoleWriter,但您可以根据需要设置日志的范围或级别。范围(记录器名称)应该是线程的唯一标识符。像这样的东西:
Logger.getLogger("Thread-00001").addAppender(appender);
您的线程应写入此记录器。
Logger.getLogger("Thread-00001").info("blah blah blah");
当你想完成记录线程时:
Logger.getLogger("Thread-00001").removeAppender("CONSOLE_APPENDER");
更新:这是一个工作示例。将错误日志写入文件(在 log4j.xml 中设置)+ 将所有线程日志写入 StringWriter,启用时:
import java.io.StringWriter;
import org.apache.log4j.Logger;
import org.apache.log4j.Level;
import org.apache.log4j.WriterAppender;
import org.apache.log4j.PatternLayout;
public class Log4jTest implements Runnable {
public static final String CONSOLE_APPENDER = "CONSOLE_APPENDER";
private static WriterAppender appender = null;
private static int counter = 1;
public static synchronized String getNextId() {
return "Thread_00"+(counter++);
}
public void run() {
String id="UNKNOWN";
try {
id = getNextId();
Logger log = Logger.getLogger(id);
log.addAppender(appender);
log.setLevel(Level.DEBUG);
log.info(id+" log message 1");
log.removeAppender(CONSOLE_APPENDER);
log.info(id+" log message 2");
log.error(id+" log message 3");
} catch (Exception e) {
System.out.println("Error in "+id);
e.printStackTrace();
}
}
public static void main(String [] args) {
try {
StringWriter consoleWriter = new StringWriter();
appender = new WriterAppender(new PatternLayout("%d{ISO8601} %p - %m%n"),consoleWriter);
appender.setName(CONSOLE_APPENDER);
appender.setThreshold(org.apache.log4j.Level.DEBUG);
for (int i=0; i<5; i++) {
Thread t = new Thread(new Log4jTest());
t.start();
}
Thread.sleep(200);
System.out.println(consoleWriter.getBuffer().toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
这是我的 log4j.xml:
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration>
<appender name="FILE" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="./Log4jTest.log" />
<param name="MaxFileSize" value="1000KB" />
<param name="MaxBackupIndex" value="5" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ISO8601} %p - %m%n" />
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMin" value="WARN" />
<param name="LevelMax" value="FATAL" />
</filter>
</appender>
<root>
<level value="ERROR" />
<appender-ref ref="FILE" />
</root>
</log4j:configuration>