在SpringBoot项目中添加logback的MDC

时间:2022-07-13 22:40:15

先看下MDC是什么

Mapped Diagnostic Context,用于打LOG时跟踪一个“会话“、一个”事务“。举例,有一个web controller,在同一时间可能收到来自多个客户端的请求,如果一个请求发生了错误,我们要跟踪这个请求从controller开始一步步都执行到了哪些代码、有哪些log的输出。这时我们可以看log文件,但是log文件是多个请求同时记录的,基本无法分辨哪行是哪个请求产生的,虽然我们可以看线程,但线程可能被复用,也是很难分辨出,这时MDC就派上用场了。

我们可以加一个web filter,在请求进来时,把”标识“放到MDC context中,比如:put( ip, 8.8.8.8), put(username, 'yang'),在filter结束时把context再清掉,即可在整个请求处理过程中,都可以打印出ip, username这些数据,就可以方便的用于日志跟踪。

在SpringBoot中怎么用

1. 写一个LogInterceptor,用于统一处理MDC:

  1.  
    @Component
  2.  
    public class LogInterceptor implements HandlerInterceptor {
  3.  
     
  4.  
    private final static String REQUEST_ID = "requestId";
  5.  
    private static final Logger LOGGER = LoggerFactory.getLogger(LogInterceptor.class);
  6.  
     
  7.  
    @Override
  8.  
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
  9.  
    String xForwardedForHeader = httpServletRequest.getHeader("X-Forwarded-For");
  10.  
    String remoteIp = httpServletRequest.getRemoteAddr();
  11.  
    String uuid = UUID.randomUUID().toString();
  12.  
    LOGGER.info("put requestId ({}) to logger", uuid);
  13.  
    LOGGER.info("request id:{}, client ip:{}, X-Forwarded-For:{}", uuid, remoteIp, xForwardedForHeader);
  14.  
    MDC.put(REQUEST_ID, uuid);
  15.  
    return true;
  16.  
    }
  17.  
     
  18.  
    @Override
  19.  
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
  20.  
    String uuid = MDC.get(REQUEST_ID);
  21.  
    LOGGER.info("remove requestId ({}) from logger", uuid);
  22.  
    MDC.remove(REQUEST_ID);
  23.  
    }
  24.  
     
  25.  
    @Override
  26.  
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
  27.  
     
  28.  
    }
  29.  
    }
关键代码在于:MDC.put(REQUEST_ID, uuid);

2. 注册一下这个Interceptor,写一个WebMvcConfigurer类:

  1.  
    @Configuration
  2.  
    public class WebMvcConfigurer extends WebMvcConfigurerAdapter {
  3.  
    @Autowired
  4.  
    private LogInterceptor logInterceptor;
  5.  
     
  6.  
    @Override
  7.  
    public void addInterceptors(InterceptorRegistry registry) {
  8.  
    registry.addInterceptor(logInterceptor);
  9.  
    super.addInterceptors(registry);
  10.  
    }
  11.  
    }
3. 放一个logback.xml到src/main/resources/目录中,用于配置logback的参数,如没有,请新建一个
  1.  
    <configuration scan="true" scanPeriod="30 seconds" debug="true">
  2.  
     
  3.  
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
  4.  
    <target>System.out</target>
  5.  
    <encoder>
  6.  
    <pattern>[%date{ISO8601}] [%-5level] - [%thread] [%X{requestId}] [%logger] [%X{akkaSource}] - %msg %rootException %n
  7.  
    </pattern>
  8.  
     
  9.  
    </encoder>
  10.  
    </appender>
  11.  
     
  12.  
     
  13.  
     
  14.  
    <root level="INFO">
  15.  
    <appender-ref ref="STDOUT"/>
  16.  
    </root>
  17.  
     
  18.  
    </configuration>

注意这个<pattern/>中配置了输出 requestId

4. 最后看下效果,下面加粗的即为requestId
[2017-12-14 16:08:45,677] [INFO ] - [http-nio-8080-exec-1] [a08f86cd-6743-48ce-816a-f5ee61b802b8]