我从Michael S.提出了这个想法,但是就像在一条评论中提到的那样,它存在一些问题:它无法捕获所有内容,并且会打印一些空白行。
我也想分开System.out
和System.err
,以便System.out
使用日志级别记录日志,'INFO'
并System.err
使用'ERROR'
(或者,'WARN'
如果愿意)进行日志记录。
所以这是我的解决方案:首先是一个扩展类OutputStream
(覆盖for的所有方法OutputStream
比for容易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)));
}
}