tags:

views:

17

answers:

2

Hello,

Is there a way for me to intercept the STDERR stream that is being used from an external JAR file?

My situation is that I have my own program using STDERR for XYZ, and an external JAR that uses STDERR for ABC. I want to merge both so that they are formatted correctly for the end user, but I cannot figure out how to catch or redirect or (what is the right term?) the JAR's STDERR?

Thanks,

+2  A: 

The standard error stream in java programs is System.err and standard output stream is System.out.

You can override these both using the System.setErr(java.io.PrintStream) and System.setOut to a PrintStream object. But this will be replaced globally. Provide an implementation of a PrintStream that will do the formatting and set this as an standard error stream for both.

If you have two different processes, then you can get another processes's error stream (as an input stream) read content from it (fromat it) and write it to your standard error stream.

naikus
The problem here is that I don't know when/what each JAR is printing. E.g. I need to know which JAR they're coming from so that I can actually format them correctly. No way to detect what is coming from which JAR?
gnucom
A: 

Not an easy solution, but you could create a classloader, java agent or preprocessor that modifies the bytecode of selected classes and replaces all references to the static field System.err to access your custom output stream.

Jörn Horstmann
Creative, but not the right way to do it.
TheLQ