Sunday, March 27, 2011

How to log console output ?

What is Console Output

Any output that is produced by System.out.

Redirect vs Logging

The previous article talked about redirecting System.out. Redirecting means to store the console output to a file, without actually printing to the Console Window. Logging means that the output is print to the console window as normal, but those output are saved to a log file as well for other purpose(such as debugging, auditing,...etc).

How ?

A small modification of the sample program in the previous article would serve the purpose.

* File :
* Author :
* Description :
*   A class to log the console output
* Tested with : JDK 1.6

public class SystemOutLogger extends
  private consoleOut=null;

  // initialize a file output stream, also save the console output stream to a variable
  public SystemOutLogger() throws Exception
      consoleOut = System.out;

  // override the print() method so that it prints to file as well as console
  public void print(String s)
    super.print(s);        // write to file
    consoleOut.print(s);   // write to console

  // override println() with String parameter
  public void println(String s)

  // override println() without parameter
  public void println()

  // Testing program, which can be placed in another source file if you wish
  public static void main(String[] args) throws Exception
    SystemOutLogger logger = new SystemOutLogger();
    System.out.println("Logging output to out.txt");
    System.out.print("Hello, ");   // no line break, 
    System.out.println("World !"); // "Hello World !" would be on the same line
    System.out.println();          // Add an empty line
    System.out.println("Thanks for visiting");

Thanks for reading. Comments are welcome.

No comments:

Post a Comment