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