Я применил базовую идею этого, и она отлично работает.
Нет необходимости менять все содержимое System.out. ### и System.err. ###.
import java.io.OutputStream;
import java.io.PrintStream;
import de.msg.pm.designer.services.simulation.junit.base.Defines;
public class Interceptor extends PrintStream
{
/** the logger */
private Logger log;
/** the origin output stream */
PrintStream orig;
/**
* Initializes a new instance of the class Interceptor.
*
* @param out the output stream to be assigned
* @param log the logger
*/
public Interceptor( OutputStream out, Logger log )
{
super( out, true );
this.log = log;
}
/**
* {@inheritDoc}
*/
@Override
protected void finalize() throws Throwable
{
detachOut();
super.finalize();
}
/**
* {@inheritDoc}
*/
@Override
public void print( String s )
{
//do what ever you like
orig.print( s );
log.logO( s, true );
}
/**
* {@inheritDoc}
*/
@Override
public void println( String s )
{
print( s + Defines.LF_GEN );
}
/**
* Attaches System.out to interceptor.
*/
public void attachOut()
{
orig = System.out;
System.setOut( this );
}
/**
* Attaches System.err to interceptor.
*/
public void attachErr()
{
orig = System.err;
System.setErr( this );
}
/**
* Detaches System.out.
*/
public void detachOut()
{
if( null != orig )
{
System.setOut( orig );
}
}
/**
* Detaches System.err.
*/
public void detachErr()
{
if( null != orig )
{
System.setErr( orig );
}
}
}
public class InterceptionManager
{
/** out */
private Interceptor out;
/** err */
private Interceptor err;
/** log */
private Logger log;
/**
* Initializes a new instance of the class InterceptionManager.
*
* @param logFileName the log file name
* @param append the append flag
*/
public InterceptionManager( String logFileName, boolean append )
{
log = new Logger();
log.setLogFile( logFileName, append );
this.out = new Interceptor( System.out, log );
this.out.attachOut();
this.err = new Interceptor( System.err, log );
this.err.attachErr();
}
/**
* {@inheritDoc}
*/
@Override
protected void finalize() throws Throwable
{
if( null != log )
{
log.closeLogFile();
}
super.finalize();
}
}
Эти несколько строк включат ведение журнала без дальнейших изменений кода:
if( writeLog )
{
this.logFileName = this.getClassName() + "_Log.txt";
this.icMan = new InterceptionManager( this.logFileName, false );
System.out.format( "Logging to '%s'\n", this.logFileName );
}