写在前面

通过本文将了解到什么是MDC、MDC应用中存在的问题、如何解决存在的问题

MDC介绍

简介:

MDC(Mapped Diagnostic Context,映射调试上下文)是 log4j 、logback及log4j2 提供的一种方便在多线程条件下记录日志的功能。MDC 可以看成是一个与当前线程绑定的哈希表,可以往其中添加键值对。MDC 中包含的内容可以被同一线程中执行的代码所访问
当前线程的子线程会继承其父线程中的 MDC 的内容。当需要记录日志时,只需要从 MDC 中获取所需的信息即可。MDC 的内容则由程序在适当的时候保存进去。对于一个 Web 应用来说,通常是在请求被处理的最开始保存这些数据

API说明:
  • clear() => 移除所有MDC
  • get (String key) => 获取当前线程MDC中指定key的值
  • getContext() => 获取当前线程MDC的MDC
  • put(String key, Object o) => 往当前线程的MDC中存入指定的键值对
  • remove(String key) => 删除当前线程MDC中指定的键值对

    优点:

    代码简洁,日志风格统一,不需要在log打印中手动拼写traceId,即LOGGER.info(“traceId:{} “, traceId)
    暂时只能想到这一点

    MDC使用

    添加拦截器

    1. public class LogInterceptor implements HandlerInterceptor {
    2. @Override
    3. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    4. //如果有上层调用就用上层的ID
    5. String traceId = request.getHeader(Constants.TRACE_ID);
    6. if (traceId == null) {
    7. traceId = TraceIdUtil.getTraceId();
    8. }
    9. MDC.put(Constants.TRACE_ID, traceId);
    10. return true;
    11. }
    12. @Override
    13. public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
    14. throws Exception {
    15. }
    16. @Override
    17. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
    18. throws Exception {
    19. //调用结束后删除
    20. MDC.remove(Constants.TRACE_ID);
    21. }
    22. }
  • 修改日志格式

    1. <property name="pattern">[TRACEID:%X{traceId}] %d{HH:mm:ss.SSS} %-5level %class{-1}.%M()/%L - %msg%xEx%n</property>

    重点是%X{traceId},traceId和MDC中的键名称一致
    简单使用就这么容易,但是在有些情况下traceId将获取不到

MDC 存在的问题

  • 子线程中打印日志丢失traceId
  • HTTP调用丢失traceId

……丢失traceId的情况,来一个再解决一个,绝不提前优化

解决MDC存在的问题

子线程日志打印丢失traceId

子线程在打印日志的过程中traceId将丢失,解决方式为重写线程池,对于直接new创建线程的情况不考略【实际应用中应该避免这种用法】,重写线程池无非是对任务进行一次封装
线程池封装类:ThreadPoolExecutorMdcWrapper.java

  1. public class ThreadPoolExecutorMdcWrapper extends ThreadPoolExecutor {
  2. public ThreadPoolExecutorMdcWrapper(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
  3. BlockingQueue<Runnable> workQueue) {
  4. super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
  5. }
  6. public ThreadPoolExecutorMdcWrapper(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
  7. BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {
  8. super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
  9. }
  10. public ThreadPoolExecutorMdcWrapper(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
  11. BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) {
  12. super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);
  13. }
  14. public ThreadPoolExecutorMdcWrapper(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
  15. BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory,
  16. RejectedExecutionHandler handler) {
  17. super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
  18. }
  19. @Override
  20. public void execute(Runnable task) {
  21. super.execute(ThreadMdcUtil.wrap(task, MDC.getCopyOfContextMap()));
  22. }
  23. @Override
  24. public <T> Future<T> submit(Runnable task, T result) {
  25. return super.submit(ThreadMdcUtil.wrap(task, MDC.getCopyOfContextMap()), result);
  26. }
  27. @Override
  28. public <T> Future<T> submit(Callable<T> task) {
  29. return super.submit(ThreadMdcUtil.wrap(task, MDC.getCopyOfContextMap()));
  30. }
  31. @Override
  32. public Future<?> submit(Runnable task) {
  33. return super.submit(ThreadMdcUtil.wrap(task, MDC.getCopyOfContextMap()));
  34. }
  35. }

说明:

  • 继承ThreadPoolExecutor类,重新执行任务的方法
  • 通过ThreadMdcUtil对任务进行一次包装

线程traceId封装工具类:ThreadMdcUtil.java

  1. public class ThreadMdcUtil {
  2. public static void setTraceIdIfAbsent() {
  3. if (MDC.get(Constants.TRACE_ID) == null) {
  4. MDC.put(Constants.TRACE_ID, TraceIdUtil.getTraceId());
  5. }
  6. }
  7. public static <T> Callable<T> wrap(final Callable<T> callable, final Map<String, String> context) {
  8. return () -> {
  9. if (context == null) {
  10. MDC.clear();
  11. } else {
  12. MDC.setContextMap(context);
  13. }
  14. setTraceIdIfAbsent();
  15. try {
  16. return callable.call();
  17. } finally {
  18. MDC.clear();
  19. }
  20. };
  21. }
  22. public static Runnable wrap(final Runnable runnable, final Map<String, String> context) {
  23. return () -> {
  24. if (context == null) {
  25. MDC.clear();
  26. } else {
  27. MDC.setContextMap(context);
  28. }
  29. setTraceIdIfAbsent();
  30. try {
  31. runnable.run();
  32. } finally {
  33. MDC.clear();
  34. }
  35. };
  36. }
  37. }

说明【以封装Runnable为例】:

  • 判断当前线程对应MDC的Map是否存在,存在则设置
  • 设置MDC中的traceId值,不存在则新生成,针对不是子线程的情况,如果是子线程,MDC中traceId不为null
  • 执行run方法

代码等同于以下写法,会更直观

  1. public static Runnable wrap(final Runnable runnable, final Map<String, String> context) {
  2. return new Runnable() {
  3. @Override
  4. public void run() {
  5. if (context == null) {
  6. MDC.clear();
  7. } else {
  8. MDC.setContextMap(context);
  9. }
  10. setTraceIdIfAbsent();
  11. try {
  12. runnable.run();
  13. } finally {
  14. MDC.clear();
  15. }
  16. }
  17. };
  18. }

重新返回的是包装后的Runnable,在该任务执行之前【runnable.run()】先将主线程的Map设置到当前线程中【 即MDC.setContextMap(context)】,这样子线程和主线程MDC对应的Map就是一样的了

  • 判断当前线程对应MDC的Map是否存在,存在则设置
  • 设置MDC中的traceId值,不存在则新生成,针对不是子线程的情况,如果是子线程,MDC中traceId不为null
  • 执行run方法

    HTTP调用丢失traceId

    在使用HTTP调用第三方服务接口时traceId将丢失,需要对HTTP调用工具进行改造,在发送时在request header中添加traceId,在下层被调用方添加拦截器获取header中的traceId添加到MDC中
    HTTP调用有多种方式,比较常见的有HttpClient、OKHttp、RestTemplate,所以只给出这几种HTTP调用的解决方式
    HttpClient:

  • 实现HttpClient拦截器

    1. public class HttpClientTraceIdInterceptor implements HttpRequestInterceptor {
    2. @Override
    3. public void process(HttpRequest httpRequest, HttpContext httpContext) throws HttpException, IOException {
    4. String traceId = MDC.get(Constants.TRACE_ID);
    5. //当前线程调用中有traceId,则将该traceId进行透传
    6. if (traceId != null) {
    7. //添加请求体
    8. httpRequest.addHeader(Constants.TRACE_ID, traceId);
    9. }
    10. }
    11. }

    实现HttpRequestInterceptor接口并重写process方法
    如果调用线程中含有traceId,则需要将获取到的traceId通过request中的header向下透传下去

  • 为HttpClient添加拦截器

    1. private static CloseableHttpClient httpClient = HttpClientBuilder.create()
    2. .addInterceptorFirst(new HttpClientTraceIdInterceptor())
    3. .build();

通过addInterceptorFirst方法为HttpClient添加拦截器
OKHttp:

  • 实现OKHttp拦截器

    1. public class OkHttpTraceIdInterceptor implements Interceptor {
    2. @Override
    3. public Response intercept(Chain chain) throws IOException {
    4. String traceId = MDC.get(Constants.TRACE_ID);
    5. Request request = null;
    6. if (traceId != null) {
    7. //添加请求体
    8. request = chain.request().newBuilder().addHeader(Constants.TRACE_ID, traceId).build();
    9. }
    10. Response originResponse = chain.proceed(request);
    11. return originResponse;
    12. }
    13. }

    实现Interceptor拦截器,重写interceptor方法,实现逻辑和HttpClient差不多,如果能够获取到当前线程的traceId则向下透传

  • 为OkHttp添加拦截器

    1. private static OkHttpClient client = new OkHttpClient.Builder()
    2. .addNetworkInterceptor(new OkHttpTraceIdInterceptor())
    3. .build();

    调用addNetworkInterceptor方法添加拦截器
    RestTemplate:

  • 实现RestTemplate拦截器

    1. public class RestTemplateTraceIdInterceptor implements ClientHttpRequestInterceptor {
    2. @Override
    3. public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
    4. String traceId = MDC.get(Constants.TRACE_ID);
    5. if (traceId != null) {
    6. httpRequest.getHeaders().add(Constants.TRACE_ID, traceId);
    7. }
    8. return clientHttpRequestExecution.execute(httpRequest, bytes);
    9. }
    10. }

    实现ClientHttpRequestInterceptor接口,并重写intercept方法,其余逻辑都是一样的不重复说明

  • 为RestTemplate添加拦截器

    1. restTemplate.setInterceptors(Arrays.asList(new RestTemplateTraceIdInterceptor()));

    调用setInterceptors方法添加拦截器
    第三方服务拦截器:
    HTTP调用第三方服务接口全流程traceId需要第三方服务配合,第三方服务需要添加拦截器拿到request header中的traceId并添加到MDC中

    1. public class LogInterceptor implements HandlerInterceptor {
    2. @Override
    3. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    4. //如果有上层调用就用上层的ID
    5. String traceId = request.getHeader(Constants.TRACE_ID);
    6. if (traceId == null) {
    7. traceId = TraceIdUtils.getTraceId();
    8. }
    9. MDC.put("traceId", traceId);
    10. return true;
    11. }
    12. @Override
    13. public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
    14. throws Exception {
    15. }
    16. @Override
    17. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
    18. throws Exception {
    19. MDC.remove(Constants.TRACE_ID);
    20. }
    21. }

    说明:

  • 先从request header中获取traceId

  • 从request header中获取不到traceId则说明不是第三方调用,直接生成一个新的traceId
  • 将生成的traceId存入MDC中

除了需要添加拦截器之外,还需要在日志格式中添加traceId的打印,如下:

  1. <property name="pattern">[TRACEID:%X{traceId}] %d{HH:mm:ss.SSS} %-5level %class{-1}.%M()/%L - %msg%xEx%n</property>

需要添加%X{traceId}