java微服务不侵入业务代码的情况下快速追踪一个请求链路中各个服务的运行日志

背景
在使用微服务中,由于调用链路进一步的复杂,同一个请求可能会在不同的机器,jvm和线程中运行这样就造成了日志的发散和查找的困难,发散问题我们可以通过日志收集,重新聚合,例如ELK等,但是聚合的日志查找整个链路的日志依然非常困难,这里介绍一种方案,原理其实很简单,就是通过请求时随机生成一个requestId,然后将requestId存入每个线程中作为一个变量,打印日志时从线程中取出,打印在日志中,这样就可以通过requestId来追踪请求链路中所有的日志信息了。本文主要讲述,requestId如何生成以及在各个微服务和线程间传递。

一、介绍requestId生成方案

(1)可以客户端生成,采用uuid生成的方式即可,也可以用其他方式,保证唯一性即可,通过url发送请求时传入。
(2)如果客户端没有生成,可以在程序入口统一拦截处理生成唯一requestId。

二、日志中自动带入requestId,不侵入业务程序。

这个例子采用了logback,也可以使用其他的日志工具方法大同小异利用spring aop在方法入口处调用,将requestId存入线程变量中

 MdcRunable.setRequestIdIfAbsent(requestId);

在方法结束时调用

 MDC.clear();

利用spring aop实现例子:

 @Around("@annotation(autoLog)")
    public Object systemWebLogMonitor(ProceedingJoinPoint joinPoint, AutoLog autoLog) throws Throwable {
        // 获取参数类型
        Object result;
        Object[] params = joinPoint.getArgs();
        String username = getUser(),
                logString = getMethodInfo(joinPoint);
        String requestId = null, url = "", headers = "";
        StopWatch stopWatch = new StopWatch();

        //requestId用于日志追踪使用
        if (Objects.nonNull(RequestContextHolder.getRequestAttributes())) {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            //获取request
            headers = getHeaders(request);
            //请求url
            url = request.getRequestURI();
            requestId = request.getParameter(REQUEST_ID);
        }
        MdcRunable.setRequestIdIfAbsent(requestId);
       
        result = joinPoint.proceed();
  
        MDC.clear();
        return result;
    }

logback配置文件配置日志格式

<configuration>
    <include resource="org/springframework/boot/logging/logback/defaults.xml"/>
    <property name="FILE_LOG_PATTERN" value="[%d{yyyy-MM-dd HH:mm:ss.SSS}] [%thread] [%level] [%X{requestId}] [%file:%line] [%msg] %n"/>
</configuration>

这样就可以在日志中打印出requestId

三、如何将requestId传入Hystrix线程中

直接上代码,重写HystrixConcurrencyStrategy中的wrapCallable方法,将requestId传入,这样就可以将requestId带到Hystrix的线程池中了

import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy;
import com.sunlands.zlcx.usercenter.common.thread.MdcRunable;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.concurrent.Callable;

@Slf4j
@Primary
@Service
public class HystrixConcurrencyStrategyDecorator extends HystrixConcurrencyStrategy {
    @Override
    public <T> Callable<T> wrapCallable(Callable<T> callable) {
        return super.wrapCallable(MdcRunable.wrap(callable, MDC.getCopyOfContextMap()));
    }
}

四、如何将值传入被调用的微服务中

通过重写Client.Default类,将线程中的requestId赋值到url中,微服务中的接口参考一中例子接受requestId后将值放入线程变量中,就可以向下传递

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import feign.*;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.netflix.feign.ribbon.CachingSpringLoadBalancerFactory;
import org.springframework.cloud.netflix.feign.ribbon.LoadBalancerFeignClient;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import org.springframework.cloud.security.oauth2.client.feign.OAuth2FeignRequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails;
import org.springframework.stereotype.Component;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSocketFactory;
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.Collections;
import java.util.Objects;
import static com.sunlands.zlcx.usercenter.common.interceptor.AutoLogAspect.REQUEST_ID;

/**
 * @author anjl
 * 使用feign时,使用此配置
 */
@Configuration
@EnableConfigurationProperties
@Slf4j
public class OauthFeignConfig {

   

    public OauthFeignConfig() {
    }

    @Bean
    public Client feignClient(CachingSpringLoadBalancerFactory cachingFactory, SpringClientFactory clientFactory) {
        return new LoadFeignBalancerFeignClient(new DefaultClient(null, null), cachingFactory, clientFactory);
    }


    class LoadFeignBalancerFeignClient implements Client {
        private LoadBalancerFeignClient loadBalancerFeignClient;

        public LoadFeignBalancerFeignClient(Client delegate, CachingSpringLoadBalancerFactory lbClientFactory, SpringClientFactory clientFactory) {
            loadBalancerFeignClient = new LoadBalancerFeignClient(delegate, lbClientFactory, clientFactory);
        }

        @Override
        public Response execute(Request request, Request.Options options) throws IOException {
            URI asUri = URI.create(request.url());
            String clientName = asUri.getHost();
            DefaultClient delegate = (DefaultClient) loadBalancerFeignClient.getDelegate();
            delegate.setClientName(clientName);
            return loadBalancerFeignClient.execute(request, options);
        }
    }


    class DefaultClient extends Client.Default implements Client {
        private String clientName;

        public void setClientName(String clientName) {
            this.clientName = clientName;
        }

        public DefaultClient(SSLSocketFactory sslContextFactory, HostnameVerifier hostnameVerifier) {
            super(sslContextFactory, hostnameVerifier);
        }

        @Override
        public Response execute(Request request, Request.Options options) throws IOException {
            

            if (Objects.nonNull(MDC.get(REQUEST_ID))) {
                String url = request.url();

                if (url.contains("?")) {
                    url = url + "&" + REQUEST_ID + "=" + MDC.get(REQUEST_ID);
                } else {
                    url = url + "?" + REQUEST_ID + "=" + MDC.get(REQUEST_ID);
                }
                request = Request.create(request.method(), url, request.headers(), request.body(), request.charset());
            }

            return super.execute(request, options);
        }
    }

    /**--------------------end--------------------------**/

    /**
     * 系统访问有oauth验证的服务时,通过注入一个ClientCredentialsResourceDetails用于换区token
     *
     * @return ClientCredentialsResourceDetails
     */
    @Bean
    @ConfigurationProperties(prefix = "security.oauth2.client")
    public ClientCredentialsResourceDetails clientCredentialsResourceDetails() {
        return new ClientCredentialsResourceDetails();
    }

    /**
     * 给feign访问添加一个OAuth2FeignRequestInterceptor,用于在header中放入token
     *
     * @return RequestInterceptor
     */
    @Bean
    public RequestInterceptor oauth2FeignRequestInterceptor() {
        ClientCredentialsResourceDetails client = clientCredentialsResourceDetails();
        try {
            log.debug("oauth2FeignRequestInterceptor={}", new ObjectMapper().writeValueAsString(client));
        } catch (JsonProcessingException e) {
            log.warn("oauth2FeignRequestInterceptor", e);
        }
        return new OAuth2FeignRequestInterceptor(new DefaultOAuth2ClientContext(), client);
    }

    @Bean
    public OAuth2RestTemplate clientCredentialsRestTemplate() {
        ClientCredentialsResourceDetails client = clientCredentialsResourceDetails();
        try {
            log.debug("clientCredentialsRestTemplate={}", new ObjectMapper().writeValueAsString(client));
        } catch (JsonProcessingException e) {
            log.warn("clientCredentialsRestTemplate", e);
        }
        return new OAuth2RestTemplate(client);
    }

    /**
     * feign调用出错后处理
     *
     * @return ErrorDecoder
     */
    @Bean
    public ErrorDecoder errorDecoder() {
        return (methodKey, response) -> {
            try {
                Request request = response.request();
                String message = "调用微服务出错:code = " + response.status() + "    request = " + request + "    response = " + response;

                return new MyFeignException(response.status(), message);
            } catch (Exception e) {
                return FeignException.errorStatus(response.status() + "", response);
            }
        };
    }

    @SuppressWarnings("WeakerAccess")
    public static class MyFeignException extends FeignException {
        private MyFeignException(int status, String message) {
            super(status, message);
        }
    }


    /**
     * 避免在应用关闭的时候产生: Error creating bean with name 'eurekaAutoServiceRegistration': Singleton bean creation not allowed
     */
    @Component
    public static class FeignBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

        private static final String EUREKA_AUTO_SERVICE_REGISTRATION = "eurekaAutoServiceRegistration";
        private static final String FEIGN_CONTEXT = "feignContext";

        @Override
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
            if (containsBeanDefinition(beanFactory, FEIGN_CONTEXT, EUREKA_AUTO_SERVICE_REGISTRATION)) {
                BeanDefinition bd = beanFactory.getBeanDefinition(FEIGN_CONTEXT);
                bd.setDependsOn(EUREKA_AUTO_SERVICE_REGISTRATION);
            }
        }

        private boolean containsBeanDefinition(ConfigurableListableBeanFactory beanFactory, String... beans) {
            return Arrays.stream(beans).allMatch(beanFactory::containsBeanDefinition);
        }
    }

    @Bean
    Logger.Level feignLoggerLevel() {
        //这里记录所有,根据实际情况选择合适的日志level
        return Logger.Level.FULL;
    }


}

五、最后如何解决,异步线程执行,requestId的传递问题

重写类ThreadPoolTaskExecutorDecorator

package com.sunlands.zlcx.usercenter.common.thread;

import org.slf4j.MDC;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;

/**
 * @ClassName ThreadPoolTaskExecutorDecorator
 * @Destription 线程重写类
 * @AUTHOR anjl
 *
 * @VERSION 1.0
 **/
public class ThreadPoolTaskExecutorDecorator extends ThreadPoolTaskExecutor {

    private static final long serialVersionUID = -9132702922468298050L;

    @Override
    public <T> Future<T> submit(Callable<T> task) {
        // 传入线程池之前先复制当前线程的MDC
        return super.submit(MdcRunable.wrap(task, MDC.getCopyOfContextMap()));
    }

    @Override
    public Future<?> submit(Runnable task) {
        return super.submit(MdcRunable.wrap(task, MDC.getCopyOfContextMap()));
    }

    @Override
    public void execute(Runnable task) {
        super.execute(MdcRunable.wrap(task, MDC.getCopyOfContextMap()));
    }


}
//线程池定义
  @Bean("asyncExecutor")
    public AsyncTaskExecutor asyncExecutor() {
        return getThreadPoolTaskScheduler(1,  "asyncExecutor", true);
    }

    private ThreadPoolTaskScheduler getThreadPoolTaskScheduler(int corePoolSize, String threadNamePrefix, boolean waitForTasksToCompleteOnShutdown) {
        ThreadPoolTaskScheduler executor = new ThreadPoolTaskSchedulerDecorator();
        executor.setPoolSize(corePoolSize);
        executor.setThreadNamePrefix(threadNamePrefix);
        //设置线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean,这样这些异步任务的销毁就会先于外部资源的销毁
        executor.setWaitForTasksToCompleteOnShutdown(waitForTasksToCompleteOnShutdown);
        //用来设置线程池中任务的等待时间,如果超过这个时候还没有销毁就强制销毁,以确保应用最后能够被关闭,而不是阻塞住
        executor.setRejectedExecutionHandler(new AbortPolicy());
        executor.setErrorHandler(new ErrorHandlerImpl());
        return executor;
    }
 //调用:
 sendError.execute(() -> {
            //
        });

以上对整个业务代码无侵入,增加整个业务逻辑的日志追踪requestId,当要查询一个调用链路的全部日志时,只需要根据requestId进行搜索即可准确找出所有的日志信息。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,548评论 6 513
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,069评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,985评论 0 357
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,305评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,324评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,030评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,639评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,552评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,081评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,194评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,327评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,004评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,688评论 3 332
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,188评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,307评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,667评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,337评论 2 358