springboot+logback实现简单的日志追踪

1、首先需要生成sessionId放置到MDC变量中,代码如下

import org.slf4j.MDC;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

public class SessionInterceptor extends HandlerInterceptorAdapter {
    /**
     * 会话ID
     */
    private final static String SESSION_KEY = "sessionId";


    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
                           Object arg2, ModelAndView arg3) throws Exception {
    }

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {

        String token = UUID.randomUUID().toString().replaceAll("-","");
        //本例测试使用sessionId,也可以使用UUID等
//        String token = request.getSession().getId();
        MDC.put(SESSION_KEY, token);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest arg0,
                                HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        // 删除
        MDC.remove(SESSION_KEY);
    }
}

2、接着在WebMvcConfigurer中创建一个拦截器

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Bean
    public SessionInterceptor getSessionInterceptor() {
        return new SessionInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getSessionInterceptor()).addPathPatterns("/**");
    }


}

3、最后在logback-spring.xml配置中添加打印的sessionId

    
    
        
        
        
        
            %d{yyyy-MM-dd HH:mm:ss} [%X{sessionId}] [%class:%line] - %m%n
        
        
        
            
            INFO
            
            ACCEPT
            
            DENY
        
        
        
            
            ${log.home}/info/%d{yyyy-MM-dd}-info.%i.log.zip
            
            30
            
                
                256 MB
            
        
    

4、展示结果

 

你可能感兴趣的:(日志打印,spring,boot,logback,servlet)