log4j的WriterAppender的应用
这几天做项目,需要做一个类似于控制台的界面,可以将日志回显到一个文本区域里,几经查找,反复测试写了以下测试代码。
这是log4j.properties的配置内容
log4j.rootCategory= ,WriterAppender
log4j.appender.WriterAppender=org.apache.log4j.WriterAppender
log4j.appender.WriterAppender.Threshold=debug
log4j.appender.WriterAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.WriterAppender.layout.ConversionPattern=%d{ISO8601} - %p - %m%n
主程序
import java.io.PipedReader;
import java.io.PipedWriter;
import java.io.Writer;import org.apache.log4j.Appender;
import org.apache.log4j.Logger;
import org.apache.log4j.WriterAppender;public class Log4jMain {
??? static public Logger logger = Logger.getLogger(Log4jMain.class);??? public static void main(String[] arg) {
???????
???????
??????? Logger root = Logger.getRootLogger();
??????? try {
??????????? Appender appender = root.getAppender("WriterAppender");
??????????? PipedReader reader = new PipedReader();
??????????? Writer writer = new PipedWriter( reader) ;
???????
??????????? ((WriterAppender) appender).setWriter(writer);
???????????
??????????? Thread t = new AaaThread(reader);
??????????? t.start();
??????????? Logger logger = Logger.getLogger(Log4jMain.class);
??????????? logger.error("asdf");
??????????? logger.info("asdf");
??????????? logger.debug("asdf");
??????????? logger.fatal("asdf");
??????????????? //hh是一个class,test方法里只有几个logger.info("aaa"),用于测试用,这东西可以去掉
??????????? new HH().test();??????? } catch (Exception e) {
??????? }??? }
???
}
?????? 因为log4j提供的是 Writer,所以通过使用PipedWriter连接到PipedReader,并通过一个thread来处理 PipedReader的数据就可以回显了。如果你需要的话可以将下面的 System.out.println(scanner.nextLine());改成你需要显示的地方就行了。
import java.io.PipedReader;
import java.util.Scanner;public class AaaThread extends Thread {
??? PipedReader reader;??? public AaaThread(PipedReader reader) {
??????? this.reader = reader;
??? }??? public void run() {
??????? Scanner scanner = new Scanner(reader);
??????? while (scanner.hasNext()) {
??????????? System.out.println(scanner.nextLine());
??????? }
??? }
}