Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect System.out.println

My application has many System.out.println() statements.

I want to catch messages from println and send them to the standard logger (Log4j, JUL etc).

How to do that ?

like image 340
EK. Avatar asked Jul 12 '10 12:07

EK.


People also ask

Can system ERR can be redirected to a file?

Generally, stderr and stdout both send data to the console, whatever that is. However, stdout and stderr can be redirected to different places. For instance, output can be redirected to a file while error messages still appear on the console. Finished programs shouldn't have much need for System.

How do I get out of system in Java?

You can use System. setOut() to redirect the System. out.


2 Answers

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.

like image 78
paxdiablo Avatar answered Oct 06 '22 02:10

paxdiablo


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 } 
like image 40
Wizard of Kneup Avatar answered Oct 06 '22 04:10

Wizard of Kneup