用log4j来生成日志。然后将日志类加入到过滤器中。使得当用户访问时JSP或者Servlet时可以生成日志。便于调试。
下面是用log4j来的得到用户访问的地址并写道文件中。
package com.cmmi.tools;
import com.cmmi.tools.Cundate;
import Java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*; // For Date class
import org.apache.log4j.*;
public class LogFilter implements Filter {
protected FilterConfig config;
private ServletContext context;
private String filterName;
private Cundate cd=new Cundate();
//
static Logger logger = Logger.getLogger(LogFilter.class.getName());
//
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws ServletException, IOException {
HttpServletRequest req = (HttpServletRequest)request;
chain.doFilter(request,response);
//
PropertyConfigurator.configure("Log4j.properties");
LogFilter.logger.info(req.getRemoteHost()
"试图访问"
req.getRequestURL()
"在" cd.getTime4() ". "
"(被报告:" filterName ".)");
//
}
public void init(FilterConfig config)
throws ServletException {
this.config = config; // In case it is needed by subclass.
context = config.getServletContext();
filterName = config.getFilterName();
}
public void destroy() {}
}
//
得到当前日期的简单类。
package xzt.rs.tools.*;
public class Cundate{
public String getTime4(){
Date d = new Date(); //Get current date to d.
SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); //Set date format
String strDate = fm.format(d); //Get date to string strDate via format fm.
return strDate;
}
}
在Web.XML中配置过滤器,使得用户访问jsp或者servlet时把访问的文件、时间、用户写道日志中。
<filter>
<filter-name>Logger</filter-name>
<filter-class>
xzt.rs.tools.LogFilter
</filter-class>
</filter>
<!-- ... -->
<!-- Apply the Logger filter to all servlets and
JSP pages.
-->
<filter-mapping>
<filter-name>Logger</filter-name>
<url-pattern>/*.jsp</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>Logger</filter-name>
<url-pattern>/servlet/*</url-pattern>
</filter-mapping>
<!-- ... -->
生成的文件内容
INFO [tcpConnection-8080-3] (LogFilter.java:31) - newtransit试图访问http://192.168.0.3:8080/oasystem/main.jsp在2005-01-21-16-40-31. (被报告:Logger.)
Log4j.properties的配置文件
log4j.rootLogger=debug, A1
#打印到文件
log4j.appender.A1=org.apache.log4j.RollingFileAppender
log4j.appender.A1.File=F:/resin/resin-2.0.4/bak/sdcdcBak.log
log4j.appender.A1.MaxFileSize=1024KB
log4j.appender.A1.MaxBackupIndex=100
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
#打印到控制台
#log4j.appender.B1=org.apache.log4j.ConsoleAppender
#log4j.appender.B1.layout=org.apache.log4j.PatternLayout
#log4j.appender.B1.layout.ConversionPattern=%-4r %-5p [%t] 7c %3x - %m%n
#log4j.appender.B1.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n