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}来引用!