package com;java
import java.io.PrintStream;web
import javax.servlet.ServletContextEvent;apache
import javax.servlet.ServletContextListener;app
import org.apache.commons.logging.impl.LogFactoryImpl;日誌
/**xml
* 把在程序中的System.out.print()的信息自動轉成日誌信息get
*/servlet
public class StdoutListener implements ServletContextListener {it
public void contextDestroyed(ServletContextEvent event) {io
}
private void log(Object info) {
LogFactoryImpl.getLog(getClass()).info(info);
}
public void contextInitialized(ServletContextEvent event) {
PrintStream printStream = new PrintStream(System.out) {
public void println(boolean x) {
log(Boolean.valueOf(x));
}
public void println(char x) {
log(Character.valueOf(x));
}
public void println(char[] x) {
log(x == null ? null : new String(x));
}
public void println(double x) {
log(Double.valueOf(x));
}
public void println(float x) {
log(Float.valueOf(x));
}
public void println(int x) {
log(Integer.valueOf(x));
}
public void println(long x) {
log(x);
}
public void println(Object x) {
log(x);
}
public void println(String x) {
log(x);
}
};
System.setOut(printStream);
System.setErr(printStream);
}
}
在web.xml裏配置這個監聽器,完善log4j.properties文件。搞定!
附:
web.xml中配置監聽器:
<listener>
<listener-class>com.bettersoft.filters.StdoutListener</listener-class>
</listener>
個人 log4j.properties文件:
log4j.rootLogger=INFO,Stdout,R
log4j.appender.Stdout=org.apache.log4j.ConsoleAppender
log4j.appender.Stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.Stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %m%n
log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
log4j.appender.R.File=../logs/stdout.log
log4j.appender.R.datePattern='.'yyyy-MM-dd'.txt'
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %m%n