在有些系统中,由于代码历史和日志系统应用不好的原因,导致代码中出现了大量的System.out.println作为了调试的一些手段;当系统正式发布之后,只有在控制台才能看到这些信息,为了能将这些out信息输出到日志,需要对systemout重定向:
1.system本身就提供了setout方法,方法的入参为PrintStream
2.将入参改为自己些的stream类,当然要继承java.io.PrintStream
3.在自己的stream类中复写父类中的方法,println\print,在方法调用日志类,记录日志
4.在web.xml中加入一个servlet,使得在web容器加载之后就进行servlet初始化调用out重定向方法
以下为相关代码:
1.System.setOut(new Log4jPrintStream(System.out));
2.
public class Log4jPrintStream extends PrintStream {
private boolean autoFlush = false;
private boolean trouble = false;
protected ByteArrayOutputStream out = new ByteArrayOutputStream();
private static org.apache.log4j.Logger logger = org.apache.log4j.Logger
.getLogger("S");
public Log4jPrintStream(OutputStream out) {
super(out);
}
private Log4jPrintStream(OutputStream out, boolean autoFlush,
String encoding) throws UnsupportedEncodingException {
super(out, autoFlush, encoding);
this.autoFlush = autoFlush;
}
private Log4jPrintStream(OutputStream out, boolean autoFlush) {
super(out, autoFlush);
this.autoFlush = autoFlush;
}
public boolean checkError() {
super.checkError();
return trouble;
}
protected void clearError() {
trouble = false;
}
public void close() {
}
public void print(boolean b) {
println(b);
}
public void print(char c) {
println(c);
}
public void print(char[] s) {
println(s);
}
public void print(double d) {
println(d);
}
public void print(float f) {
println(f);
}
public void print(int i) {
println(i);
}
public void print(long l) {
println(l);
}
public void print(Object obj) {
println(obj);
}
public void print(String s) {
println(s);
}
public void println() {
}
public void println(boolean x) {
logger.info(x + "");
}
public void println(char x) {
logger.info(x + "");
}
public void println(char[] x) {
logger.info(x == null ? null : new String(x));
}
public void println(double x) {
logger.info(x + "");
}
public void println(float x) {
logger.info(x + "");
}
public void println(int x) {
logger.info(x + "");
}
public void println(long x) {
logger.info(x + "");
}
public void println(Object x) {
logger.info(x + "");
}
public void println(String x) {
logger.info(x);
}
protected void setError() {
super.setError();
trouble = true;
}
public void write(byte[] b, int off, int len) {
try {
synchronized (this) {
out.write(b, off, len);
if (autoFlush)
out.flush();
}
} catch (InterruptedIOException x) {
Thread.currentThread().interrupt();
} catch (IOException x) {
x.printStackTrace();
trouble = true;
}
}
public void flush() {
try {
out.flush();
String ret = out.toString();
println(ret.trim());
out.reset();
} catch (Throwable e) {
e.printStackTrace();
out.reset();
}
}
public void write(int b) {
println(b);
}
public void write(byte[] b) throws IOException {
out.write(b);
}
}