vda8888
vda8888

Reputation: 707

Stdout redirection with Logger

I am trying to redirect my output to a text area (that's going to be embedded somewhere in a JFrame using the following piece of code

public static void main(String[] args) {
    Logger.getLogger(MyClass.class.getName()).info("Test");

    final JTextArea x = new JTextArea();

    PrintStream printStream = new PrintStream(new OutputStream(){
        @Override
        public void write(int b) throws IOException {
            x.append(String.valueOf((char)b));
               x.setCaretPosition(x.getDocument().getLength());
        }
    });

    System.setOut(printStream);
    System.setErr(printStream);

    Logger.getLogger(MyClass.class.getName()).info("Test again");
    System.out.println("Another test");

    JOptionPane.showMessageDialog(null, x.getText());
}

However, when the last line executed, the JOptionPane text was only "Another test". When I remove the first Logger line

Logger.getLogger(MyClass.class.getName()).info("Test");

Then everything is redirected to the JTextArea. I suspect that after I log "Test" in the first line, the class Logger binds to the console output and won't give up even if the stdout is redirected to TextArea.

Upvotes: 0

Views: 554

Answers (1)

jmehrens
jmehrens

Reputation: 11045

The first line of your main method captures the current System.err stream. If you remap the streams before creating the root logger handlers it will work. You could also change the code to create a new ConsoleHandler and add it to the root logger after you have remapped the error stream. Look out for violating the EDT rules of Swing with your current implementation.

Upvotes: 1

Related Questions