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 : SystemOutLogger.java
* Author : http://java.macteki.com/
* Description :
* A class to log the console output
* Tested with : JDK 1.6
******************************************************************************/
public class SystemOutLogger extends java.io.PrintStream
{
private java.io.PrintStream consoleOut=null;
// initialize a file output stream, also save the console output stream to a variable
public SystemOutLogger() throws Exception
{
super(new java.io.FileOutputStream("out.txt"),true);
consoleOut = System.out;
System.setOut(this);
}
// 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)
{
print(s+"\n");
}
// override println() without parameter
public void println()
{
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 java.macteki.com");
}
}
Thanks for reading. Comments are welcome.
No comments:
Post a Comment