Springboot starter开发之traceId请求日志链路追踪

简介: 能标识一次请求的完整流程,包括日志打印、响应标识等,以便于出现问题可以快速定位并解决问题。

一、请求链路追踪是什么?



能标识一次请求的完整流程,包括日志打印、响应标识等,以便于出现问题可以快速定位并解决问题。


二、使用步骤



1. 相关知识点


ThreadLocal:一种保证一种规避多线程访问出现线程不安全的方法,当我们在创建一个变量后,如果每个线程对其进行访问的时候访问的都是线程自己的变量这样就不会存在线程不安全问题。


MDC:(Mapped Diagnostic Context,映射调试上下文)是 log4j 和 logback 提供的一种方便在多线程条件下记录日志的功能,基于ThreadLocal实现的一种工具类。


拦截器:基于拦截器对每个请求注入traceId。


2. 代码实现


1.封装TraceId工具类:


/**
 * @author yinfeng
 * @description traceId工具类
 * @since 2021/10/2 11:10
 */
public class TraceIdUtil {
    private static final String TRACE_ID = "traceId";
    public static void set() {
        MDC.put(TRACE_ID, generate());
    }
    public static String get() {
        return MDC.get(TRACE_ID);
    }
    public static void remove() {
        MDC.remove(TRACE_ID);
    }
    public static String generate() {
        return UUID.randomUUID().toString().replace("-", "").substring(0, 16);
    }
}


2.springboot环境注入工具类

/**
 * @author yinfeng
 * @description 资源配置工具类
 * @since 2021/10/2 0:02
 */
public class PropertySourcesUtil {
    private static final String NAME = "aop.yinfeng";
    private static ConfigurableEnvironment environment;
    private static SpringApplication application;
    public static void setEnvironment(ConfigurableEnvironment environment) {
        if (PropertySourcesUtil.environment == null) {
            PropertySourcesUtil.environment = environment;
        }
    }
    public static SpringApplication getApplication() {
        return application;
    }
    public static void setApplication(SpringApplication application) {
        PropertySourcesUtil.application = application;
    }
    public static void set(String key, Object value) {
        getSourceMap().put(key, value);
    }
    public static Object get(String key) {
        return getSourceMap().get(key);
    }
    public static Map<String, Object> getSourceMap() {
        PropertySource<?> propertySource = environment.getPropertySources().get(NAME);
        Map<String, Object> source;
        if (propertySource == null) {
            source = new LinkedHashMap<String, Object>();
            propertySource = new MapPropertySource(NAME, source);
            environment.getPropertySources().addLast(propertySource);
        }
        source = (Map<String, Object>) propertySource.getSource();
        return source;
    }
}


3.支持配置的日志实体类:


/**
 * @author yinfeng
 * @description 日志配置类
 * @since 2021/10/1 17:45
 */
@Data
@ConfigurationProperties(prefix = "aop.logging")
public class LogProperties {
    private String logDir;
    // 因为logback和log4j的日志格式略有不同,所以提供2种打印格式
    private String logbackPattern = "%d{yyyy-MM-dd HH:mm:ss.SSS} %X{traceId} %-5level %logger{30} : %msg%n";
    private String log4jPattern = "%d{yyyy-MM-dd HH:mm:ss.SSS} %X{traceId} %-5level %clr{%-30.30c{1.}}{cyan} : %msg%n";
}

4.环境增强注入配置:


因为请求链路追踪在各个服务中比较常用,所以以starter的形式进行封装,在spring环境加载后进行配置注入。

/**
 * @author yinfeng
 * @description 环境注入抽象类
 * @since 2021/10/1 17:55
 */
public abstract class AbstractEnvironmentPostProcessor implements EnvironmentPostProcessor {
    private static final String DEV = "dev";
    private static final String STG = "stg";
    private static final String PRD = "prod";
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        PropertySourcesUtil.setEnvironment(environment);
        final List<String> profiles = Arrays.asList(environment.getActiveProfiles());
        if (profiles.contains(PRD)) {
            doPrd(environment, application);
        } else if (profiles.contains(STG)) {
            doStg(environment, application);
        } else {
            doDev(environment, application);
        }
        onProfile(environment, application);
    }
    protected void doPrd(ConfigurableEnvironment environment, SpringApplication application) {
    }
    protected void doStg(ConfigurableEnvironment environment, SpringApplication application) {
    }
    protected void doDev(ConfigurableEnvironment environment, SpringApplication application) {
    }
    protected void onProfile(ConfigurableEnvironment environment, SpringApplication application) {
    }
}


/**
 * @author yinfeng
 * @description 日志环境注入
 * @since 2021/10/1 17:52
 */
@EnableConfigurationProperties(LogProperties.class)
public class LogEnvAdvice extends AbstractEnvironmentPostProcessor {
    @Override
    protected void onProfile(ConfigurableEnvironment environment, SpringApplication application) {
        final Binder binder = Binder.get(environment);
        final BindResult<LogProperties> bindResult = binder.bind("aop.logging", Bindable.of(LogProperties.class));
        LogProperties logProperties = new LogProperties();
        if (bindResult.isBound()) {
            logProperties = bindResult.get();
        }
        // 配置日志打印格式
        if (isLogback(application)) {
            PropertySourcesUtil.set("logging.pattern.console", logProperties.getLogbackPattern());
            PropertySourcesUtil.set("logging.pattern.file", logProperties.getLogbackPattern());
            return;
        }
        PropertySourcesUtil.set("logging.pattern.console", logProperties.getLog4jPattern());
        PropertySourcesUtil.set("logging.pattern.file", logProperties.getLog4jPattern());
    }
    /**
     * 判断是否是logback日志格式
     *
     * @param application application
     * @return
     */
    private boolean isLogback(SpringApplication application) {
        final LoggingSystem loggingSystem = LoggingSystem.get(application.getClassLoader());
        return LogbackLoggingSystem.class.equals(loggingSystem.getClass());
    }
}


5.在spring.factory文件配置log环境注入类


org.springframework.boot.env.EnvironmentPostProcessor=com.yinfeng.common.enviroment.LogEnvAdvice


6.配置拦截器,在每个请求进入时注入traceId,因为基于threadLocal实现,所以需要在请求完成后进行手动清除,否则gc会扫描不到


/**
* @author yinfeng
* @description 日志拦截器
* @since 2021/10/2 11:09
*/
public class LogInterceptor implements HandlerInterceptor {
   @Override
   public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
       TraceIdUtil.set();
       return true;
   }
   /**
    * 回收资源,防止oom
    * @param request
    * @param response
    * @param handler
    * @param ex
    * @throws Exception
    */
   @Override
   public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
       TraceIdUtil.remove();
   }
}


/**
 * @author yinfeng
 * @description 拦截器增强
 * @since 2021/10/2 11:15
 */
public class InterceptorAdvice implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
      // 将拦截器注入到容器中
        final InterceptorRegistration registration = registry.addInterceptor(new LogInterceptor()).order(Integer.MIN_VALUE);
        registration.addPathPatterns("/**");
    }
}


3. 测试一下效果


到此为止,通过traceId追踪请求链路代码基本完成,下面咱们来测认识一下


  1. 在pom文件中引入咱们的starter


<dependency>
    <groupId>com.yinfeng</groupId>
    <artifactId>common-starter</artifactId>
    <version>1.0.0</version>
    <exclusions>
        <exclusion>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
        </exclusion>
        <exclusion>
            <groupId>com.github.jsqlparser</groupId>
            <artifactId>jsqlparser</artifactId>
        </exclusion>
    </exclusions>
</dependency>


2..通过knife4j接口文档发送请求


image.png


3.查看日志:可以看到咱们所有的业务日志打印都会带上traceId,方便咱们快速定位问题


image.png


三、总结



下一节咱们来说对全局响应体包装和traceId链路追踪的结合。


相关实践学习
【涂鸦即艺术】基于云应用开发平台CAP部署AI实时生图绘板
【涂鸦即艺术】基于云应用开发平台CAP部署AI实时生图绘板
目录
相关文章
|
存储 监控 数据库
Django 后端架构开发:高效日志规范与实践
Django 后端架构开发:高效日志规范与实践
569 1
|
Rust 前端开发 JavaScript
Tauri 开发实践 — Tauri 日志记录功能开发
本文介绍了如何为 Tauri 应用配置日志记录。Tauri 是一个利用 Web 技术构建桌面应用的框架。文章详细说明了如何在 Rust 和 JavaScript 代码中设置和集成日志记录,并控制日志输出。通过添加 `log` crate 和 Tauri 日志插件,可以轻松实现多平台日志记录,包括控制台输出、Webview 控制台和日志文件。文章还展示了如何调整日志级别以优化输出内容。配置完成后,日志记录功能将显著提升开发体验和程序稳定性。
1362 1
Tauri 开发实践 — Tauri 日志记录功能开发
|
SQL 关系型数据库 MySQL
【MySQL】根据binlog日志获取回滚sql的一个开发思路
【MySQL】根据binlog日志获取回滚sql的一个开发思路
|
前端开发 JavaScript 程序员
鸿蒙开发:console日志输出
针对初学者而言,大家只需要掌握住日志打印即可,等到了鸿蒙应用开发的时候,还有一个鸿蒙原生的打印工具HiLog,到时,我们也会详细的去讲述,也会针对HiLog,封装一个通用的工具类。
634 11
鸿蒙开发:console日志输出
|
XML 人工智能 Java
java通过自定义TraceId实现简单的链路追踪
本文介绍了如何在Spring Boot项目中通过SLF4J的MDC实现日志上下文traceId追踪。内容涵盖依赖配置、拦截器实现、网关与服务间调用的traceId传递、多线程环境下的上下文同步,以及logback日志格式配置。适用于小型微服务架构的链路追踪,便于排查复杂调用场景中的问题。
616 0
|
监控 开发者
鸿蒙5.0版开发:使用HiLog打印日志(ArkTS)
在HarmonyOS 5.0中,HiLog是系统提供的日志系统,支持DEBUG、INFO、WARN、ERROR、FATAL五种日志级别。本文介绍如何在ArkTS中使用HiLog打印日志,并提供示例代码。通过合理使用HiLog,开发者可以更好地调试和监控应用。
1191 16
|
JSON 中间件 Go
go语言后端开发学习(四) —— 在go项目中使用Zap日志库
本文详细介绍了如何在Go项目中集成并配置Zap日志库。首先通过`go get -u go.uber.org/zap`命令安装Zap,接着展示了`Logger`与`Sugared Logger`两种日志记录器的基本用法。随后深入探讨了Zap的高级配置,包括如何将日志输出至文件、调整时间格式、记录调用者信息以及日志分割等。最后,文章演示了如何在gin框架中集成Zap,通过自定义中间件实现了日志记录和异常恢复功能。通过这些步骤,读者可以掌握Zap在实际项目中的应用与定制方法
1089 1
go语言后端开发学习(四) —— 在go项目中使用Zap日志库
|
开发工具 git
git显示开发日志+WinSW——将.exe文件注册为服务的一个工具+图床PicGo+kubeconfig 多个集群配置 如何切换
git显示开发日志+WinSW——将.exe文件注册为服务的一个工具+图床PicGo+kubeconfig 多个集群配置 如何切换
467 1
|
开发框架 缓存 安全
开发日志:IIS安全配置
开发日志:IIS安全配置
开发日志:IIS安全配置
|
小程序 前端开发 API
微信小程序全栈开发中的异常处理与日志记录是一个重要而复杂的问题。
微信小程序作为业务拓展的新渠道,其全栈开发涉及前端与后端的紧密配合。本文聚焦小程序开发中的异常处理与日志记录,从前端的网络、页面跳转等异常,到后端的数据库、API调用等问题,详述了如何利用try-catch及日志框架进行有效管理。同时强调了集中式日志管理的重要性,并提醒开发者注意安全性、性能及团队协作等方面,以构建稳定可靠的小程序应用。
473 1