java - 将 log4j 语句重定向到 java 中的自定义控制台

标签 java logging log4j

下面的类使用一个 JInternalFrame 来保存一个显示所有重定向的 println 和 err 语句的 Textarea。

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[])north.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);
    }

  }

}

此类仅重定向 sysout 和 syserr 语句。我应该在代码中进行哪些修改以将记录器语句重定向到文本区域?

最佳答案

您应该实现自定义 Log4J 记录器。有非常有用的基类可以扩展。我建议使用 org.apache.log4j.WriterAppender

关于java - 将 log4j 语句重定向到 java 中的自定义控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5645440/

相关文章:

java - 将整数传递给 int,反之亦然

java - Spring JMS 消息不会重试或在错误时进入回退队列

java - 如何检查 JFrame 中选中了哪些复选框?

java - 如何在 Java 中重用 redis(JRedis) 连接池

ruby-on-rails - 在日志消息之前添加当前时间

mysql - perl 解码西里尔字母字符串

log4j - Apache commons HTTPClient 和 log4j.xml

grails - 在DEBUG级别记录我的应用程序的类,在WARN记录所有其他类

ruby - 是否有适用于 Ruby 的异步日志记录库?

java - 关闭 hibernate 日志到控制台