开发者

Redirecting log4j statements to custom console in java

The following class uses a JInternalFrame holding a Textarea that displays all the redirected println and err statements.

public class ConsoleFrame extends JInternalFrame
{
  JTextArea outArea = new JTextArea(10,100);
  static JInternalFrame cons;
  public ConsoleFrame() 
  {
    outArea.setLineWrap(true);
    JScrollPane pain = new JScrollPane(outArea);
    //pain.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
    this.add(pain);
    this.setVisible(true);
    this.setSize(1000,400); 
    this.setTitle("Groovy Console");
    this.closable = false;
    this.maximizable = false;
    this.isSelected = true;
    this.resizable = false;
    BasicInternalFrameUI ui = (BasicInternalFrameUI)this.getUI();
    Component north = ui.getNorthPane();
    MouseMotionListener[] actions =
    (MouseMotionListener[])nort开发者_C百科h.getListeners(MouseMotionListener.class);

    for (int i = 0; i < actions.length; i++)
    north.removeMouseMotionListener( actions[i] );

    this.setFocusable(false);    
 //logger
    System.setErr(new PrintStream(new JTextAreaOutputStream(outArea)));
    System.setOut(new PrintStream(new JTextAreaOutputStream(outArea)));

    setConsole(this);
  }


  static public JInternalFrame getConsole(){
      return cons;
  }
  public void setConsole(JInternalFrame console){
      cons = console;
  }
  public class JTextAreaOutputStream extends OutputStream {
    JTextArea ta;

    public JTextAreaOutputStream(JTextArea t) {
      super();
      ta = t;
    }

    public void write(int i) {
      ta.append(Character.toString((char)i));
    }

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

  }

}

This class only redirects the sysout and syserr statements. What modification should I make in the code to redirect the logger statements into the textarea?


You should implement a custom Log4J logger. There are very useful base classes to extend from. I would recommend using a org.apache.log4j.WriterAppender.


The Log4J logger is probably getting its references to System.out and System.err before you replace them. So you can either implement a custom Appender, or try to beat Log4J to the punch. The latter may be possible if you have control of startup.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜