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);

Advertisements

7 thoughts on “System.out and System.err over log4j

  1. KampfSogge says:

    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);

  2. yameen says:

    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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s