重定向System.out.println

EK.*_*EK. 32 java logging out redirectstandardoutput

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

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

怎么做 ?

pax*_*blo 35

该系统类有一个setOutsetErr可以用来改变输出流,例如,一个新的PrintStream与背衬File或者,在这种情况下,很可能它使用你选择的日志记录子系统的另一个流.


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

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


Wiz*_*eup 30

我曾经有类似的需求.我需要拦截某些第三方组件的输出并对错误消息做出反应.这个概念看起来像这样:

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
}
Run Code Online (Sandbox Code Playgroud)

  • 好主意.谢谢 (2认同)

Ste*_*all 9

更好的解决方案是通过并更改所有println语句以使用正确的日志记录库.你要做的是一个大黑客.

  • 我普遍同意,但正如我在上面的回答中提到的,我需要拦截第三方System.out消息.没有其它的方法.因此,有一个用例.GOTO甚至还有一个用例:-) (3认同)

Vic*_*yew 6

以下是如何将打印捕获到 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();
Run Code Online (Sandbox Code Playgroud)