32

我的应用程序有许多 System.out.println() 语句。

我想从 println 捕获消息并将它们发送到标准记录器(Log4j、JUL 等)。

怎么做 ?

4

6 回答 6

38

System 类有一个setOutand setErr,可以用来将输出流更改为,例如,一个PrintStream带有支持的新流,File或者在这种情况下,可能是另一个使用您选择的日志子系统的流。


请记住,如果您将日志库配置为输出到标准输出或错误(可能是无限递归类型),您很可能会遇到麻烦。

如果是这种情况,您可能只想System.out.print用真正的日志调用替换您的 -type 语句。

于 2010-07-12T12:25:32.860 回答
33

我曾经有过类似的需求。我需要拦截一些第 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
}
于 2010-07-13T05:40:24.477 回答
9

更好的解决方案是检查并更改所有 println 语句以使用适当的日志记录库。你想要做的是一个大黑客。

于 2010-07-12T12:27:37.077 回答
4

以下是如何将打印内容捕获到 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();
于 2016-04-11T19:54:09.157 回答
3

扩展 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);
于 2017-08-25T07:08:30.613 回答
-2

我应用了这个的基本思想,它工作得很好。无需更改所有 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 );
  }
于 2013-07-04T11:37:41.920 回答