How to redirect System.out.println in Java

Did you ever get frustrated with a codebase which has overuse of System.out.println??
May be it is flooding your console or even worse you need to capture the outputs to analyze them….Ever wondered how you can capture your System.out.println() ‘s of your tomcat application?? Well, you can always use IO Redirect in unix to send the output to a file. You can use find replace to change all System.out.println() to some method call which will write the logs to a file. But being the lazy programmer that I am, I always look for a shortcut. And sometimes I even find one 🙂
I was working with this code and it had important System.out.println everywhere. I wanted to use trail/grep and stuffs like that with the console logs but I couldn’t do that on the application console. So this is what I did to redirect all System.out.println to a log file.

public class MyMainClass {   public static void main(String[] args) throws FileNotFoundException {

    File file  = new File(\"/home/sajid/sysout.log\");   
    PrintStream printStream = new PrintStream(new FileOutputStream(file));

    System.out.println(\"1\");

    System.setOut(printStream);

    System.out.println(\"2\");

}}

Did you ever notice that System.out is just another PrintStream and you can replace it with your own? This is why I love java. You can replace many things with your own implementation. Did I tell you how I replaced the URLClassLoader with my JDBCClassLoader to load classes from Database? Lets keep that story for another post.

Advertisements

4 thoughts on “How to redirect System.out.println in Java

  1. @Dayl:

    Quick trick is to save the previous System.out into some static variable/cache before you change it. For example:

    PrintStream realSystemOut = System.out;

    now set it back like this:

    System.setOut(realSystemOut);

    It should work.

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s