log4j记录登陆用户相关操作

1、web.xml中添加过滤器

<!-- LoggerMDCFilter,存放在MDC中的数据,log4j可以直接引用并作为日志信息打印出来. -->
	<filter>
		<filter-name>LoggerMDCFilter</filter-name>
		<filter-class>javacommon.filter.LoggerMDCFilter</filter-class>
	</filter>

	<filter-mapping>
		<filter-name>LoggerMDCFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

 2、编写过滤器类

package javacommon.filter;

import java.io.IOException;
import java.util.Map;
import java.util.UUID;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.MDC;
import org.springframework.web.filter.OncePerRequestFilter;

import com.winksi.mis.util.Const;

import sun.reflect.ReflectionFactory.GetReflectionFactoryAction;
/**
 * 存放在MDC中的数据,log4j可以直接引用并作为日志信息打印出来.
 * 
 * <pre>
 * 示例使用:
 * log4j.appender.stdout.layout.conversionPattern=%d [%X{loginUserId}/%X{req.remoteAddr}/%X{req.id} - %X{req.requestURI}?%X{req.queryString}] %-5p %c{2} - %m%n
 * </pre>
 * @author badqiu
 */
public class LoggerMDCFilter extends OncePerRequestFilter implements Filter{
    
    protected void doFilterInternal(HttpServletRequest request,HttpServletResponse response, FilterChain chain)throws ServletException,IOException {
        try {
            //示例为一个固定的登陆用户,请直接修改代码
        	if(request.getSession(false) != null){
//        		String loginUserName = (String)request.getSession(false).getAttribute(Const.SESSION_LOGIN_NAME);
        		String loginUserId = (String)request.getSession(false).getAttribute(Const.SESSION_LOGIN_ID);
        		if(loginUserId != null)
        			MDC.put("loginUserId", loginUserId);
        		else
        			MDC.put("loginUserId", "nouser");
        	}
            
            MDC.put("req.requestURI", StringUtils.defaultString(request.getRequestURI()));
            MDC.put("req.queryString", StringUtils.defaultString(request.getQueryString()));
            MDC.put("req.requestURIWithQueryString", request.getRequestURI() + (request.getQueryString() == null ? "" : "?"+request.getQueryString()));
            MDC.put("req.remoteAddr", StringUtils.defaultString(request.getRemoteAddr()));
            
            //为每一个请求创建一个ID,方便查找日志时可以根据ID查找出一个http请求所有相关日志
            MDC.put("req.id", StringUtils.remove(UUID.randomUUID().toString(),"-")); 
            chain.doFilter(request, response);
        }finally {
            clearMDC();
        }
    }

    private void clearMDC() {
        Map map = MDC.getContext();
        if(map != null) {
            map.clear();
        }
    }
}

2-1编辑log4j.properties

# This is the configuring for logging displayed in the Application Server
#log4j.rootCategory=INFO, stdout,project-dao,project-web,project-service
log4j.rootLogger=INFO, common-all, stdout
log4j.logger.custmis=INFO, project-dao
#log4j.rootCategory=DEBUG,INFO, stdout,common-all,common-warn,common-error
################################
# common appenders
################################
#stdout configure
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#log4j.appender.stdout.layout.conversionPattern= %d [%X{loginUserId}/%X{req.remoteAddr}/%X{req.id} - %X{entranceMethod} - %X{req.requestURIWithQueryString}] %-5p %c - %m%n
log4j.appender.stdout.layout.conversionPattern= %d [%X{loginUserId} - %X{entranceMethod} - %X{req.requestURIWithQueryString}] %-5p %c - %m%n

#common-all file appender
log4j.appender.common-all=org.apache.log4j.DailyRollingFileAppender
log4j.appender.common-all.file=${user.home}/logs/damon_common-all.log
log4j.appender.common-all.layout=org.apache.log4j.PatternLayout
log4j.appender.common-all.layout.conversionPattern= %d [%X{loginUserId}/%X{req.remoteAddr}/%X{req.id} - %X{entranceMethod} - %X{req.requestURIWithQueryString}] %-5p %c - %m%n

#common-warn file appender
log4j.appender.common-warn=org.apache.log4j.DailyRollingFileAppender
log4j.appender.common-warn.file=${user.home}/logs/common-warn.log
log4j.appender.common-warn.layout=org.apache.log4j.PatternLayout
log4j.appender.common-warn.threshold=WARN
log4j.appender.common-warn.layout.conversionPattern= %d [%X{loginUserId}/%X{req.remoteAddr}/%X{req.id} - %X{entranceMethod} - %X{req.requestURIWithQueryString}] %-5p %c - %m%n

3、输出到数据库

????

4、参考资料

如何使用log4j记录操作员的登录ID

在记录日志的时候,我们可能有这种需求,对于每个记录除了知道日志信息外,也要当前登录用户的信息。
可以这样解决:使用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的代码了

相关推荐