zoukankan      html  css  js  c++  java
  • LogBack通过MDC实现日志记录区分用户Session

    1.首先实现一个interceptor,在请求开始的时候MDC put一个Session标志,interceptor结束的时候remove掉

    public class SessionInterceptor implements HandlerInterceptor {
        /**
         * 会话ID
         */
        private final static String SESSION_KEY = "sessionId";
    
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                                 Object handler) throws Exception {
            // 放SessionId
            String token = UUID.randomUUID().toString();
            MDC.put(SESSION_KEY, token);
    
            return true;
        }
    
        public void postHandle(HttpServletRequest request, HttpServletResponse response,
                               Object handler, ModelAndView modelAndView) throws Exception {
    
        }
    
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                    Object handler, Exception ex) throws Exception {
            // 删除
            MDC.remove(SESSION_KEY);
        }
    }

    2.然后在logback相应的配置中加上seesionId的配置就可以了

     <pattern> %X{sessionId} %date [%thread] %-5level %logger{80} - %msg%n</pattern>

    MDC中的值在logback.xml文件中的pattern中用%X{key}来引用!

  • 相关阅读:
    你写的单例真的安全吗?
    CountDownLatch&&CyclicBarrier
    初步认识AQS
    Atomic底层原理
    volatile关键字
    Linux常用服务类相关命令
    线程池
    由浅入深TheradLocal
    synchronized关键字
    .net 中dapper实现事务的三种方式总结
  • 原文地址:https://www.cnblogs.com/winner-0715/p/6273645.html
Copyright © 2011-2022 走看看