log4j记录前端用户登陆信息 .

原文地址:http://blog.donews.com/ooFrank/archive/2006/02/11/722553.aspx

在记录日志的时候,我们可能有这种需求,对于每个记录除了知道日志信息外,也要当前登录用户的信息。
可以这样解决:使用log4j的MDC

在web.xml加入 Filter:
<filter>
  <filter-name>set log4j MDC for log2userId</filter-name>
  <filter-class>UserFilter</filter-class>
  </filter>
  <filter-mapping>
  <filter-name>set log4j MDC for log2userId</filter-name>
  <url-pattern>/*</url-pattern>
  </filter-mapping>

UserFilter的代码如下:
import org.apache.log4j.Logger;

import java.io.IOException;

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 javax.servlet.http.HttpSession;

import org.apache.log4j.MDC;
import org.springside.bookstore.domain.Customer;

/**
 * 记录当前使用者的信息到log4j.MDC
 * @author frank
 *
 */
public class UserFilter implements Filter {
    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger(UserFilter.class);

    private final static String DEFAULT_USERid="anonymous";
 
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest)request;
        HttpSession session= req.getSession();
        if (session==null){
            MDC.put("userId",DEFAULT_USERID);  
        }
        else{
            Customer customer=(Customer)session.getAttribute("customer");
            if (customer==null){
                MDC.put("userId",DEFAULT_USERID);
            }
            else
            {
                MDC.put("userId",customer.getLoginid());
            }
        }
        logger.info("test for MDC.");
        
        chain.doFilter(request,response);
    }

    public void init(FilterConfig fc) throws ServletException {
        
        // do nothing
        
    }

    public void destroy() {
//         do nothing
    }
}
在log4j.properties中加入新配置,示例使用jdbc存储

log4j.appender.db=org.apache.log4j.jdbc.JDBCAppender
#log4j.appender.db.BufferSize=100
log4j.appender.db.URL=jdbc:ulr
log4j.appender.db.driver=org.hsqldb.jdbcDriver
log4j.appender.db.user=sa
log4j.appender.db.password=
log4j.appender.db.sql=INSERT INTO LOG4J_MSG (LOGINID,PRIORITY,LOGDATE,CLASS,METHOD,MSG) VALUES('%X{userId}','%p','%d{yyyy-MM-dd HH:mm:ss}','%C','%M','%m')


%X{userId}:就是取出MDC的代码了