• 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的代码了
  • 相关阅读:
    Harbor-企业级Registry服务器安装配置和使用(图解)
    kubernetes(k8s)kubectl使用详解
    prometheus和zabbix的对比
    kubernetes学习:CKA考试题
    k8s网络之Flannel网络
    k8s网络主题系列:Flannel和Calico
    kubernetes基础概念
    CoreDNS系列1:Kubernetes内部域名解析原理、弊端及优化方式
    解析记录格式
    五月七号日报
  • 原文地址:https://www.cnblogs.com/tankaixiong/p/2949857.html
Copyright © 2020-2023  润新知