Tuesday, September 27, 2011

Redirecting or Ignoring System.out.println outputs

Recently one of my friend had following requirement. I guess it can be useful to anyone.
In case you want to redirect all the System.out.println() output to some file, you can do using following methods provided by System class.
System.setOut(), System.setIn() and System.setErr()

So, to redirect the output and error logs, you can simply say
    String outFile = "/tmp/sysout.log";
    System.setOut(new PrintStream(new FileOutputStream(outFile)));
    String errFile = "/tmp/syserr.log";
    System.setOut(new PrintStream(new FileOutputStream(errFile)));

Sometimes its required to hide all System.out.println outputs when the existing application is unnecessarily writing lot of outputs filling the system space and it would take some time to modify all the code. To do this, you can subclass PrintStream and override its methods for no-op.

    System.out.println("Hello, program started.");
    String filename = "D:\\sysout.log"; //or put some dummy filepath, need to this to construct PrintStream
    System.setOut(new PrintStream(new FileOutputStream(filename)) {
   
                @Override
                public void print(String paramString) {
                  //do nothing
                }

                @Override
                public void println(String paramString) {
                  //do nothing
                }
                
                //above will just hide the output for print(String) and println(String) methods.
                //override all other print/println methods so nothing gets printed at all.
              }
            );
    System.out.println("This is another string in sysout.");

No comments:

Post a Comment