I used the log4j.Logger
and I have written the log value in to a file using the FileAppender
.
Now I want to show the log value in a textare
I would write a class that extends org.apache.log4j.AppenderSkeleton and (as the API suggests) override the append(org.apache.log4j.spi.LoggingEvent) method. With the LoggingEvent you get all necessary information to build the String you want to show. Also you can control where to save those Strings. You wanted to have them in a String array - no problem. If you only want to remember the last n logging events, you could use a queue.
Here my code (passed a simple test):
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Collections;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;
public class StringArrayAppender extends AppenderSkeleton{
private Collection log;
private int size;
public StringArrayAppender(int size) {
this.log = new ArrayDeque(size);
this.size = size;
}
public String[] getLog() {
return log.toArray(new String[0]);
}
@Override
protected void append(LoggingEvent event) {
// Generate message
StringBuilder sb = new StringBuilder();
sb.append(event.getTimeStamp()).append(": ");
sb.append(event.getLevel().toString()).append(": ");
sb.append(event.getRenderedMessage().toString());
// add it to queue
if(log.size() == size) {
((ArrayDeque) log).removeFirst();
}
log.add(sb.toString());
}
@Override
public void close() {
log = Collections.unmodifiableCollection(log);
}
@Override
public boolean requiresLayout() {
return false;
}
}