我从Michael S.那里学到了这个想法,但就像在一条评论中提到的,它有一些问题:它没有捕获所有内容,并且打印了一些空行。
另外,我想将 和 分开,以便使用日志级别进行记录并记录(或者如果您愿意)。System.out
System.err
System.out
'INFO'
System.err
'ERROR'
'WARN'
这就是我的解决方案:首先是一个扩展的类(重写所有方法比覆盖)。它使用指定的日志级别进行记录,并将所有内容复制到另一个 .此外,它还检测“空”字符串(仅包含空格)并且不记录它们。OutputStream
OutputStream
PrintStream
OutputStream
import java.io.IOException;
import java.io.OutputStream;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
public class LoggerStream extends OutputStream
{
private final Logger logger;
private final Level logLevel;
private final OutputStream outputStream;
public LoggerStream(Logger logger, Level logLevel, OutputStream outputStream)
{
super();
this.logger = logger;
this.logLevel = logLevel;
this.outputStream = outputStream;
}
@Override
public void write(byte[] b) throws IOException
{
outputStream.write(b);
String string = new String(b);
if (!string.trim().isEmpty())
logger.log(logLevel, string);
}
@Override
public void write(byte[] b, int off, int len) throws IOException
{
outputStream.write(b, off, len);
String string = new String(b, off, len);
if (!string.trim().isEmpty())
logger.log(logLevel, string);
}
@Override
public void write(int b) throws IOException
{
outputStream.write(b);
String string = String.valueOf((char) b);
if (!string.trim().isEmpty())
logger.log(logLevel, string);
}
}
然后一个非常简单的实用程序类来设置和:out
err
import java.io.PrintStream;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
public class OutErrLogger
{
public static void setOutAndErrToLog()
{
setOutToLog();
setErrToLog();
}
public static void setOutToLog()
{
System.setOut(new PrintStream(new LoggerStream(Logger.getLogger("out"), Level.INFO, System.out)));
}
public static void setErrToLog()
{
System.setErr(new PrintStream(new LoggerStream(Logger.getLogger("err"), Level.ERROR, System.err)));
}
}