Redirect System.out.println

2022-09-01 09:16:25

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

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

如何做到这一点?


答案 1

System 类具有 setOutsetErr,可用于将输出流更改为(例如)具有支持的新流,或者在本例中,可能是使用所选日志记录子系统的另一个流。PrintStreamFile


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

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


答案 2

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

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
}

推荐