Yes. Logging frameworks (i.e. log4j) are best, isDebugMode
is handy in a development environment but if you really need to "tee" your stdout you can like so.
import java.io.PrintStream;
import java.io.File;
public class TeeStream extends PrintStream {
PrintStream out;
public TeeStream(PrintStream out1, PrintStream out2) {
super(out1);
this.out = out2;
}
public void write(byte buf[], int off, int len) {
try {
super.write(buf, off, len);
out.write(buf, off, len);
} catch (Exception e) {
}
}
public void flush() {
super.flush();
out.flush();
}
}
http://www.exampledepot.com/egs/java.lang/Redirect.html
// import java.io.FileOutputStream;
String dateString = new SimpleDateFormat("yyyyMMdd").format(new Date());
File logFile = new File("mylogfile_" + dateString +".log");
PrintStream logOut = new PrintStream(new FileOutputStream(logFile, true));
PrintStream teeStdOut = new TeeStream(System.out, logOut);
PrintStream teeStdErr = new TeeStream(System.err, logOut);
System.setOut(teeStdOut);
System.setErr(teeStdErr);
You'll soon find LOG.somelevel(msg)
much more manageable than System.out.println(msg)
. It is great to raise the log level when things are working well and lower the level when they aren't without deploying a debug build.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…