我有一个自定义记录器,我想将控制台中的所有 sysout 和 syserr 重定向到该自定义记录器。所以我想通过以下方式重定向 sysout 和 syserr:
- 通过扩展 ByteArrayOutputStream
然后设置 System.setErr 和 System.setOut
public class ServerLoggingPrintStream extends ByteArrayOutputStream { public ServerLoggingPrintStream() { super(); } public void write(byte[] originalBytes, int originalOffset, int originalLength) { synchronized(this) { String str = new String(originalBytes); if (str.length() == 0 || str.equals(System.getProperty("line.separator")) ) { return; } //using my custom logger named TRACE_LOGGER TRACE_LOGGER.log(LogLevel.INFO, this, "write", str); } } } ServerLoggingPrintStream serverLoggingPrintStreamStdOut_ = null; ServerLoggingPrintStream serverLoggingPrintStreamStdErr_ = null; serverLoggingPrintStreamStdErr_ = new ServerLoggingPrintStream(); System.setErr(new PrintStream(serverLoggingPrintStreamStdErr_)); serverLoggingPrintStreamStdOut_ = new ServerLoggingPrintStream(); System.setOut(new PrintStream(serverLoggingPrintStreamStdOut_));
你认为有更好的方法吗?