EK.*_*EK. 32 java logging out redirectstandardoutput
我的应用程序有许多System.out.println()语句.
我想从println捕获消息并将它们发送到标准记录器(Log4j,JUL等).
怎么做 ?
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)
更好的解决方案是通过并更改所有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();
Run Code Online (Sandbox Code Playgroud)