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配置文件配置日志格式


    
    

这样就可以在日志中打印出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  Callable wrapCallable(Callable 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  Future submit(Callable 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进行搜索即可准确找出所有的日志信息。

你可能感兴趣的:(java微服务不侵入业务代码的情况下快速追踪一个请求链路中各个服务的运行日志)