I chose the idea of Michael S., but, as mentioned in one comment, she has some problems: she does not capture everything and prints several blank lines.
I also wanted to highlight System.out and System.err , so that System.out will be logged with the 'INFO' log level and System.err will be logged with 'ERROR' (or 'WARN' if you want).
So, this is my solution: First, a class that extends OutputStream (to simplify overriding all methods for OutputStream than for PrintStream ). It is logged with the specified log level, and also copies everything to another OutputStream . It also detects "empty" lines (containing only spaces) and does not register them.
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); } }
And then a very simple utility class to install out and 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))); } }
Dario Seidl Sep 20 '11 at 1:20 2011-09-20 01:20
source share