Press "Enter" to skip to content

Redirecting the System.out and System.err streams to a Logger

I’m working on a project where no logging was done, but a lot of information is printed out to System.out and System.err (Most exceptions print out their stack traces as well).

While this is not ideal, it is much better than nothing, and this is why: You can redirect the standard output streams to any java.io.OutputStream.

I found the following code in “Covert Java – Techniques For Decompiling, Patching, And Reverse Engineering” by Alex Kalinovsky. I would suggest that anybody serious about Java read this book.

 

The code is fairly standard. You extend OutputStream and implement the write(int) method. You define a static Logger to log the messages and then you can see that the System.out messages are logged as INFO-level messages by the Logger (Line 20).

The rest of the code in the write method is all just to detect line separators. Essentially it is somewhat more complicated than it could be for performance reasons.

Because the line separator is different on Unix and Windows system, the only way to get cross-platform code is to use the “line.separator” System property. But this property is a string, and substring searches are slower than character comparisons (Especially since you are already looping through characters in any case).

So, the lineSeparatorEnd char is used to detect probable line-separators and then a substring search is used (with the actual line-separator) to confirm it and to print out the contents of the buffer.

The main method shows how you would redirect the System.out stream (Line 29). In my project, I also do a different OutputStream for System.err that logs errors.

You can see in this example, I use the built in Logger, but this is much more useful if you use Log4j and configure a file appender to log everything to file.

While this is not ideal, if you have to support existing code where debugging information or exception stack traces are printed out to the console, this is a good way to get some logging into your application without much effort.