javaweb项目记录log4j日志过滤器

-----------------------------------------------------首先是web.xml中配置过滤器---------------------------------------------


  <!-- loggerUserManager日志管理 -->
   
<filter>
    <filter-name>set loggerUserManager</filter-name>
    <filter-class>com.xxxx.LoggerUserManager</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>set loggerUserManager</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
 



-------------------------------------------------------------然后是指定路径的类---------------------------------:

import java.io.IOException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class LoggerUserManager  implements Filter{
    
    protected Logger logger = LoggerFactory.getLogger(getClass());
    
    @Override
    public void doFilter(ServletRequest request,
              ServletResponse response, FilterChain chain)
                      throws IOException, ServletException{
        
        chain.doFilter(request, response);
        try {
              HttpServletRequest req = (HttpServletRequest)request;
              SimpleDateFormat formatter = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
              Date currentTime = new Date();
              String strDate = formatter.format(currentTime);//1.时间
              
              String hostUser = req.getRemoteUser();//2.用户名
              if(null==hostUser){
                  hostUser =" ";//没有就设置为空字符串
              }
              String url = req.getRequestURL().toString();//3.请求url
              String params = req.getQueryString();//4.请求参数
              logger.info("时间为:"+strDate + ";  来自IP:" + hostUser +
                "   请求了:" + url + "?" + params);
        }catch (Exception e){
          e.printStackTrace();
        }
    }
      
    @Override
    public void destroy(){
          
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub
        
    }

}



-----------------------------------------------------------------------------最后是log4j.properties文件配置路径--------------------------------------------------------------------

log4j.rootLogger=${rootlog}, stdout, logfile

log4j.appender.logfile.File=${application.root}/WEB-INF/logs/application.log

展开阅读全文

没有更多推荐了,返回首页