Originally posted on April 14, 2005 on another blog, here is how to redirect all java’s System.out/err over the log4j stream.
Download the latest log4j library. Actually here is only one form of packaging that includes both binaries and sources.
Unpack the archive obtained and you’ll get a “contribs/JimMoore” directory inside the directory created by extracting it.
Inside your source project, where you should already have log4j configured and running, create the org.apache.log4j.contribs package and place here the contribs/JimMoore/LoggingOutputStream.java file.
Then, where you need to redirect the out/err stream, here is a sample code:
PrintStream oldOut = System.out;
PrintStream oldErr = System.err;
//redirecting System.out/err to log4j appender
System.setOut(new PrintStream(new LoggingOutputStream(logger,Level.INFO),true));
System.setErr(new PrintStream(new LoggingOutputStream(logger,Level.ERROR),true));
//restoring original System.out/err