Thursday 2 November 2017

Redirect System out and error messages to files programmatically

java.lang.System class provides setErr, setOut methods to reassign error and output streams. In this post, I am going to show how to redirect the 'System.out' messages to 'output.log' and error messages to 'error.log' by using setOut and setErr methods.

Below step-by-step procedure explains how to redirect the output and error messages to output.log and error.log files.

Step 1: Define two PrintStream instances, one should point to 'output.log' and other should point to 'error.log'.
PrintStream pOut = new PrintStream(new FileOutputStream("output.log", true));
PrintStream pErr = new PrintStream(new FileOutputStream("error.log", true));

Step 2: Set the output and error streams using setOut and setErr methods
System.setOut(pOut);
System.setErr(pErr);

Find the below working application.

Test.java
package com.sample.streams;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;

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

  try (PrintStream pOut = new PrintStream(new FileOutputStream("output.log", true));
    PrintStream pErr = new PrintStream(new FileOutputStream("error.log", true))) {
   System.setOut(pOut);
   System.setErr(pErr);

   System.out.println("Hello World");
   System.err.println("Got Error");
  }

 }
}

No comments:

Post a Comment