mdc实现日志链路追踪

bash 复制代码
配置好log4j2
 <PatternLayout pattern="[%d{yyyy-MM-dd HH:mm:ss}] [%X{TraceId}] [%p] - %l - %m%n"/>

WebMvcConfigurer
 @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getSecurityInterceptor()).addPathPatterns("/**")
                .excludePathPatterns("/swagger-resources/**")
                .excludePathPatterns("/webjars/**")
                .excludePathPatterns("**/swagger-ui.html");

        registry.addInterceptor(new AsyncHandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request,
                                     HttpServletResponse response,
                                     Object handler) throws Exception {
                response.setHeader("TraceId",TraceIdUtil.get());
                TraceIdUtil.putIfAbsent();//生成trace id放入MDC中
                return AsyncHandlerInterceptor.super.preHandle(request, response, handler);
            }

            @Override
            public void afterCompletion(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Object handler, Exception ex) throws Exception {
                TraceIdUtil.remove();//移除MDC中的trace id
                AsyncHandlerInterceptor.super.afterCompletion(request, response, handler, ex);
            }
        });
        WebMvcConfigurer.super.addInterceptors(registry);
    }

TraceIdUtil
public class TraceIdUtil {
    private static final String TRACE_ID_KEY = "TraceId";
    private TraceIdUtil() {
    }
    public static void putIfAbsent() {
        if (StringUtils.isBlank(get())) {
            put(UUID.randomUUID().toString());
        }
    }
    public static void remove() {
        if (get() != null) {
            MDC.remove(TRACE_ID_KEY);
        }
    }
    public static String get() {
        return MDC.get(TRACE_ID_KEY);
    }
    public static void put(String traceId) {
        MDC.put(TRACE_ID_KEY, traceId);
    }
}
相关推荐
haonuy*3 天前
Log4j CVE-2021-44228 漏洞复现详细教程
log4j·教程·漏洞复现·cve-2021-44228
XF小冯4 天前
Log4j2漏洞vul-hub通关教程
log4j
sevevty-seven10 天前
Redis 事务错误处理机制与开发应对策略
数据库·redis·log4j
Ziegler Han11 天前
Java的Gradle项目,使用SLF4J+Log4j2+log4j2.xml
java·log4j·slf4j
杨DaB11 天前
【项目实践】SMBMS(Javaweb版)汇总版
学习·spring·servlet·log4j
fire-flyer12 天前
Spring Boot 源码解析之 Logging
java·spring boot·spring·log4j·logging
allenXer12 天前
Spring Boot测试全景指南:JUnit 5 + Testcontainers实现单元与集成测试
spring boot·微服务·log4j
hqxstudying21 天前
java依赖注入方法
java·spring·log4j·ioc·依赖
新world21 天前
mybatis-plus从入门到入土(二):单元测试
单元测试·log4j·mybatis
编程乐学(Arfan开发工程师)1 个月前
73、单元测试-断言机制
服务器·数据库·servlet·单元测试·sqlite·log4j·mybatis