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);
    }
}
相关推荐
周杰伦fans6 天前
记一次 Visual Studio 突然报错“未能加载 Microsoft.Internal.VisualStudio.Interop”的奇葩经历
microsoft·log4j·visual studio
laplaya6 天前
C++大型项目组件通信与依赖管理实践
c++·log4j·apache
福大大架构师每日一题6 天前
ollama v0.30.7 正式发布:Hermes 桌面端落地,接口、文档、底层依赖全方位优化
golang·log4j
四问四不知7 天前
Understand Anything的初步了解
log4j
wh_xia_jun9 天前
单元测试 + Mockito 开发指南
oracle·单元测试·log4j
kTR2hD1qb10 天前
Privaze源码级避坑指南技术文章大纲
log4j
阿正的梦工坊10 天前
【Rust】10-Cargo、测试与实用开发工作流
java·rust·log4j
捏塔11 天前
完美自动生成单元测试SKILL
单元测试·log4j
AI浩12 天前
指令微调与对齐技术:SFT、RLHF、DPO、RLAIF 与 RLVR(分层式精讲)
log4j
有浔则灵12 天前
从零开始构建 AI Agent(一):理解 Eino 的 Component 抽象与流式对话
人工智能·log4j