tags:

views:

98

answers:

4

In my application there are many System.out.println statements, how can I catch messages from println and send them to standard logger (Log4j, JUL ect) thanks!

+1  A: 

See this: http://blogs.sun.com/nickstephen/entry/java_redirecting_system_out_and

Bahaa Zaid
Thanks! This is it!
EK
+6  A: 

The System class has a setOut and setErr that can be used to change the output stream to, for example, a new PrintStream with a backing File or, in this case, probably another stream which uses your logging subsystem of choice.


Keep in mind you may well get yourself into trouble if you ever configure your logging library to output to standard output or error (of the infinite recursion type, possibly).

If that's the case, you may want to just go and replace your System.out.print-type statements with real logging calls.

paxdiablo
This is the way to solve the question that EK asks; however it will only work if the logging library isn't trying to output to stdout or stderr itself.
Andrzej Doyle
Yes, that's likely to cause fairly _serious_ problems - I think it may well get in an infinitely recursive loop. If you're going to configure your logging library to use stdout/stderr, don't use this method. I'll update the answer.
paxdiablo
+3  A: 

The better solution is to go through and change all the println statements to use a proper logging library. What you're trying to do is a big hack.

Stefan Kendall
Maybe he is trying to redirect System.out to a Logger ;-)
Riduidel
+1: the whole *point* of a logging framework is to be able to abstract where you are recording the output, you should call its logging methods as your "definitive" output from the code. Not to mention, redirecting `System.out` to call the logger *appears* to work; right up to the point where one day you configure the logger to output to stdout, and **bam** - stack overflow.
Andrzej Doyle
And this is not *that* difficult. +1
Nivas
A: 

I had a similar need once. I needed to intercept the output of some 3rd party component and react on a error message. The concept looks like this:

    private class Interceptor extends PrintStream {
    public Interceptor(OutputStream out) {
        super(out, true);
    }

    @Override
    public void print(String s) {
      //do what ever you like
        super.print(s);
    }
}
    public static void main(String[] args) {
        PrintStream origOut = System.out;
        PrintStream interceptor = new Interceptor(origOut);
        System.setOut(interceptor);// just add the interceptor
    }
Wizard of Kneup