Ubuntu insights, Programming in groovy, java, et als!

Wednesday, April 04, 2012

Redirecting log4j and Print streams to Custom Console

This is a custom JTextArea that I've coded for that can redirect and display all the print streams onto it including apache's log4j statements.



class MyConsole {
static outArea, consoleScroll, consoleTab

static log = Logger.getLogger(MyConsole.class)


//redirect the current println and err streams onto custom Stream 


static setUpStreams(){
outArea = JTextArea(10,100)
System.setErr(new PrintStream(new MyStream(outArea)));
System.setOut(new PrintStream(new  MyStream (outArea)));
WriterAppender logAppender = new WriterAppender(new PatternLayout(), new    MyStream (outArea));


Logger.getRootLogger().addAppender(logAppender);
}

public MyConsole(){ 

      setUpStreams()
}

}

//custom stream to which the standard streams are redirected
public class  MyStream  extends OutputStream {
JTextArea ta;
def str = ''
def buffer = []


MyStream (JTextArea t) {
super();
ta = t;
}

//detects \n and stores the line in a buffer and then prints the whole line..

public synchronized void write(int i) {

buffer.add(Character.toString((char)i))
if(buffer.last()=='\n'){
buffer.each{
str = str + Character.toString((char)it);
}

ta.append(str)
str = ''
buffer.clear()
}


//ta.append(Character.toString((char)i));

}

public synchronized void write(char[] buf, int off, int len) {
String s = new String(buf, off, len);
ta.append(s);

}
}



PS : I tried to keep the java-ish syntax alive in the snippet. Albeit that I guess I might have resorted to groovy's sugar syntax in a couple of places. Please make the changes accordingly. 

0 comments:

Post a Comment