JTextArea as listener for log4j Logger
How can I set up a JTextArea to receive anything that I log (short of creating an interface such as "MyLoggerListener" and implementing it into my JTextArea)
EDIT:
I fixed this problem by creating a TextAreaOutputS开发者_运维技巧tream, making a printwriter with it, and adding a WriterAppender with the printwriter in the constructor.
I think @OscarRyz's approach is a reasonable idea.
However, I think you should think hard whether you should try to do this. The problem is that painting log messages into a Java GUI is likely to be CPU intensive. This is likely to make your application logging slow, and is likely to perturb the timing of your application as a result.
(Not that your application should be timing sensitive. But if you do have timing related bugs, it is not helpful if changing logging levels etc causes the application to behave differently.)
My feeling is that embedding a fancy log viewer in your application is likely to be more trouble than it is worth ...
You can try to redirect it's output to something like this Create Java console inside panel
alt text http://img122.imageshack.us/img122/5692/dibujoof2.png
That is, you can sort of subclass Console logger ( or whatever it's name is ) and redirect the output to that component.
My solution for Log4J2 is this
import java.io.Serializable;
import javax.swing.JTextArea;
import org.apache.logging.log4j.core.Filter;
import org.apache.logging.log4j.core.Layout;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.Property;
import org.apache.logging.log4j.core.layout.PatternLayout;
public class TextAreaAppender extends AbstractAppender {
private JTextArea textarea = null;
private int maxLines;
public TextAreaAppender(String name, Filter filter, Layout<? extends Serializable> layout, int maxLines, boolean ignoreExceptions, Property[] properties) {
super(name, filter, layout, ignoreExceptions, properties);
this.maxLines = maxLines;
}
@Override
public void append(LogEvent event) {
PatternLayout layout = (PatternLayout) getLayout();
textarea.append(layout.toSerializable(event));
if ((maxLines > 0) && (textarea.getLineCount() > (maxLines + 1))) {
String text = textarea.getText();
int pos = text.indexOf('\n');
text = text.substring(pos+1);
textarea.setText(text);
}
}
public void setTextArea(JTextArea textArea) {
this.textarea = textArea;
}
}
use it like this:
PatternLayout.Builder layoutbuilder = PatternLayout.newBuilder().withPattern("%-5level %logger{36} - %msg%n");
TextAreaAppender appender = new TextAreaAppender("textLog", null, layoutbuilder.build(), 200, false, null);
appender.setTextArea(textLog);
org.apache.logging.log4j.core.Logger logger = (org.apache.logging.log4j.core.Logger) LogManager.getRootLogger();
appender.start();
logger.addAppender(appender);
精彩评论