2

I have created a swing ui and redirected System.out and System.err to a text field with this code

ConsoleOutputStream cos = new ConsoleOutputStream(textColor, printStream);
System.setOut( new PrintStream(cos, true) );

ConsoleOutputStream extends ByteArrayOutputStream, and as long as nothing is executed in new threads this works as expected.

However, my application executes third party jar files which in turn creates new threads. When these threads print to System.out it gets printed in the terminal that launched my application instead of in my text field. I have looked at this link: http://maiaco.com/articles/java/threadOut.php but i'm not sure it's applicable to my problem since I have no control whatsoever over the threads. As far as my application is aware no threads (except for the main gui thread) are created.

Is there some way to redirect all System.out:s and System.err:s independent of the threads? If not, can I maybe listen to calls to System.out and then print them to my text field? Could I potentially listen to the terminal that I launched my application from and redirect all output from it to my application?

Andreascmj
  • 49
  • 7
  • 2
    System.out is not thread specific. Check when you call setOut in relation to when the thirdparty lib reads System.out. It is possible that it reads the value in and caches it itself. – Chris K Aug 07 '14 at 09:35
  • 1
    Or if the 3rd party jar is executed in its own process, it won't inherit the streams of your program. – Kayaman Aug 07 '14 at 09:37

1 Answers1

4

System.out is not thread specific. There are two possibilities:

  1. The libraries read the System.out before you redirect it and cache the value. The fix is to redirect System.out before invoking third party library code.

  2. The libraries do not use System.out. For writing to the console there are alternatives like creating a new FileOutputStream(FileDescriptor.out) and writing to it. Or using System.console().

    If this happens through one of the known logging APIs you can override the behavior by removing the default console-writing log handler and installing your own. Otherwise it’s rather hard to do. You will have to study the libraries and their API carefully to find out how to do it. Every sophisticated library will offer a way as writing messages directly to the console without offering an alternative is a really bad programming style, especially for a library.

    It’s very likely that the libraries you are using use a logging API.

Holger
  • 285,553
  • 42
  • 434
  • 765