System.out and System.err over log4j
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
System.setOut(oldOut);
System.setErr(oldErr);

That code saved my day
thanks
I’m happy for that
Hello,
That code work fine for me, but this redirect for all my web apps !
Why ?
Thanks
Dunno, maybe ’cause all your webapps run under the same VM and System.setOut is static and shared within the same VM.
I tried your method, and it worked. But this will log every line console in an extra entry in the logfile. I think this not really good.
I played a bit myself with the PrintStream and finally found another good method to redirect the System.err:
PrintStream stderrStream = System.err;
PrintStream newStderrStream = new PrintStream(stderrStream) {
@Override
public void println(Object x) {
if(x instanceof Throwable) {
Logger.getLogger(“myLogger”).error(“”, (Throwable)x);
}
super.println(x);
}
};
System.setErr(newStderrStream);
I understand now.
Thanks a lot for your reply.
Hello every one i’m facing the problem that the logs are mingling with other logs,in such a way that the System.out of one file exist another file. for example i have a runner class in which i have writer system,out its print well in respective log file, but whenever i call the Drive call method and control return back to runner class and then all the remaining system.out of runner class are redirecting in the log file of service class.