Thursday 23 May 2019

Redirect System.out.println statements to a stream or file


'java.lang.System' class provides setOut, setErr methods to redirect system output and error messages.

Redirect out stream messages to debug.log file
PrintStream outStream = new PrintStream(new FileOutputStream("/Users/krishna/Documents/debug.log", true));
System.setOut(outStream);

Redirect err stream messages to error.log file
PrintStream errStream = new PrintStream(new FileOutputStream("/Users/krishna/Documents/error.log", true));
System.setErr(errStream);

App.java
package com.sample.app;

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

public class App {

 public static void main(String args[]) throws FileNotFoundException {
  PrintStream outStream = new PrintStream(
    new FileOutputStream("/Users/krishna/Documents/debug.log", true));
  PrintStream errStream = new PrintStream(
    new FileOutputStream("/Users/krishna/Documents/error.log", true));

  System.setOut(outStream);
  System.setErr(errStream);

  System.out.println("Starting the application");
  System.err.println("Error Occurred while executing the application");
  System.out.println("Exiting the application");

 }
}

Run App.java

Open debug.log, you can see below messages.

Starting the application
Exiting the application

Open error.log, you can see below messages.
Error Occurred while executing the application


You may like


No comments:

Post a Comment