zoukankan      html  css  js  c++  java
  • 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的代码了
  • 相关阅读:
    《译》准备做一些 AR/增强现实的 翻译
    (转)两张Firefox OS 系统截图
    Hello World!
    centos7安装docker
    linux用户及组相关命令
    Go 系列教程 ——第 30 篇:错误处理
    Go 系列教程 ——第 29 篇:Defer
    linux远程管理相关命令
    linux文件目录相关命令
    centos7安装mysql-8.0.15
  • 原文地址:https://www.cnblogs.com/tankaixiong/p/2949857.html
Copyright © 2011-2022 走看看