我从 Michael S. 那里得到了这个想法,但就像在一条评论中提到的那样,它有一些问题:它不能捕获所有内容,并且会打印一些空行。
我还想分开System.out
and System.err
,以便System.out
使用日志级别记录'INFO'
并System.err
使用'ERROR'
(或者'WARN'
如果您愿意)记录。
所以这是我的解决方案:首先是一个扩展的类(覆盖所有方法 for比 forOutputStream
更容易)。它使用指定的日志级别进行记录,并将所有内容复制到另一个. 它还检测“空”字符串(仅包含空格)并且不记录它们。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)));
}
}