我的应用程序有许多 System.out.println() 语句。
我想从 println 捕获消息并将它们发送到标准记录器(Log4j、JUL 等)。
怎么做 ?
我的应用程序有许多 System.out.println() 语句。
我想从 println 捕获消息并将它们发送到标准记录器(Log4j、JUL 等)。
怎么做 ?
我曾经有过类似的需求。我需要拦截一些第 3 方组件的输出并对错误消息做出反应。这个概念看起来像这样:
private class Interceptor extends PrintStream
{
public Interceptor(OutputStream out)
{
super(out, true);
}
@Override
public void print(String s)
{//do what ever you like
super.print(s);
}
}
public static void main(String[] args)
{
PrintStream origOut = System.out;
PrintStream interceptor = new Interceptor(origOut);
System.setOut(interceptor);// just add the interceptor
}
更好的解决方案是检查并更改所有 println 语句以使用适当的日志记录库。你想要做的是一个大黑客。
以下是如何将打印内容捕获到 System.out,然后按顺序放回原处:
// Start capturing
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
System.setOut(new PrintStream(buffer));
// Run what is supposed to output something
...
// Stop capturing
System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out)));
// Use captured content
String content = buffer.toString();
buffer.reset();
扩展 PrintStream 是一个糟糕的解决方案,因为您必须覆盖所有print()
和println()
方法。相反,您可以捕获流:
public class ConsoleInterceptor {
public interface Block {
void call() throws Exception;
}
public static String copyOut(Block block) throws Exception {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
PrintStream printStream = new PrintStream(bos, true);
PrintStream oldStream = System.out;
System.setOut(printStream);
try {
block.call();
}
finally {
System.setOut(oldStream);
}
return bos.toString();
}
}
现在您可以像这样捕获它:
String result = ConsoleInterceptor.copyOut(() ->{
System.out.print("hello world");
System.out.print('!');
System.out.println();
System.out.println("foobar");
});
assertEquals("hello world!\nfoobar\n", result);
我应用了这个的基本思想,它工作得很好。无需更改所有 System.out.### 和 System.err.### 的东西。
import java.io.OutputStream;
import java.io.PrintStream;
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 )
{
logFileName = this.getClassName() + "_Log.txt";
icMan = new InterceptionManager( logFileName, false );
System.out.format( "Logging to '%s'\n", logFileName );
}