Google Tag Manager

2015/02/25

Logging into the JTextArea

Code

Logger logger = Logger.getLogger(TextAreaLogger.TEST.getClass().getName());
logger.setUseParentHandlers(false);
OutputStream os = new TextAreaOutputStream(new JTextArea());
logger.addHandler(new TextAreaHandler(os));
logger.info("test, TEST");

//...
class TextAreaHandler extends StreamHandler {
  private void configure() {
    setFormatter(new SimpleFormatter());
    try {
      setEncoding("UTF-8");
    } catch (IOException ex) {
      try {
        setEncoding(null);
      } catch (IOException ex2) {
        // doing a setEncoding with null should always work.
        // assert false;
        ex2.printStackTrace();
      }
    }
  }
  public TextAreaHandler(OutputStream os) {
    super();
    configure();
    setOutputStream(os);
  }
  //@see java/util/logging/ConsoleHandler.java
  @Override public void publish(LogRecord record) {
    super.publish(record);
    flush();
  }
  @Override public void close() {
    flush();
  }
}

References

2 comments:

  1. I am new with this topic and I need help, I have a class with several methods that contain logs, I want to print those logs in a JTextArea while the program is running.

    ReplyDelete
    Replies
    1. Sorry, I missed your comment. It may be too late, and furthermore I may not have understood the intent of your question correctly, but the "javaagent" option may be helpful.

      https://ateraimemo.com/data/swing/loggeragent.zip

      > "%JAVA_HOME%\bin\java" -javaagent:loggeragent.jar -jar example.jar

      public class DebugLoggerAgent {
      public static void premain(String args) throws Exception {
      EventQueue.invokeLater(() -> {
      JTextArea textArea = new JTextArea(10, 20);
      textArea.setEditable(false);
      try {
      OutputStream os = new TextAreaOutputStream(textArea);
      PrintStream ps = new PrintStream(os, true, "UTF-8");
      System.setOut(ps);
      System.setErr(ps);
      } catch (IOException ex) {
      ex.printStackTrace();
      }
      System.out.println("test");

      JFrame frame = new JFrame("JTextArea Logger");
      frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(new JScrollPane(textArea));
      frame.pack();
      frame.setVisible(true);
      });
      }
      }

      Delete