Redirecting Java STDOUT from JRuby

Recently I’ve been working on a project that implements a daemon process using JRuby and the raad gem. There are also some 3rd party java libraries being used such as the new relic jar to monitor the JVM. One issue that I ran into is that some of the 3rd party java code would occasionally send output to STDOUT or STDERR. This output was essentially lost since only the ruby output was able to be redirected by the raad gem.

After some trial and error, I finally came up with a solution to redirect the output into the ruby STDOUT and STDERR so it would go wherever  those streams were being sent. Here is the code that accomplishes that:

require 'java'
printstream =

The ‘require java’ in line 1 allows you to access the standard java libraries as ruby. Line 2 constructs a PrintStream object from ruby’s STDOUT using the JRuby provided to_outputstream method. Finally, the last two lines redirect Java’s stdout and stderr to that stream.

If you use this code, be sure to place it before you java libraries get loaded since during initialization before logging systems are available is where you are most likely to lose some output to these streams.

Leave a Reply

Your email address will not be published. Required fields are marked *