log4j中MDC用法


在记录日志的时候,我们可能有这种需求,对于每个记录除了知道日志信息外,也要当前登录用户的信息。
可以这样解决:使用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>
public class UserFilter implements Filter {
    
    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的代码了
posted @ 2013-03-08 13:57  itank  阅读(18714)  评论(1编辑  收藏  举报