我的应用程序中有许多System.out.println()语句。
我想捕获来自println的消息并将它们发送到标准记录器(Log4j,JUL等)。
如何做到这一点?
我的应用程序中有许多System.out.println()语句。
我想捕获来自println的消息并将它们发送到标准记录器(Log4j,JUL等)。
如何做到这一点?
PrintStream
存储起来并在之后恢复它不是更好吗?如果还有其他东西也重定向了System.out
,这样做不一定能正确地恢复它。 - neuralmer我曾经也有类似的需求。我需要拦截一些第三方组件的输出并在出现错误消息时做出反应。 这个概念看起来像这样:
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(String s)
方法。 - gaborschSystem.out
以调用记录器似乎可以工作;直到有一天您配置记录器将输出到stdout,然后砰-堆栈溢出。 - Andrzej Doyle以下是如何捕获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 );
}