欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

日志链路追踪

程序员文章站 2022-07-03 12:35:43
...
LogInterceptor
package cn.com.autoax.config;

import com.sun.istack.internal.Nullable;
import org.slf4j.MDC;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * 〈一句话功能简述〉<br> 
 * 〈〉
 *
 * @author xiaoxiong14764
 * @create 2021/8/24
 * @since 1.0.0
 */
public class LogInterceptor extends HandlerInterceptorAdapter {

    private static final String REQUEST_ID_KEY = "requestId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String tid = UUID.randomUUID().toString().replace("-", "");
        MDC.put(REQUEST_ID_KEY, tid);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                @Nullable Exception ex) throws Exception {
        MDC.remove(REQUEST_ID_KEY);
    }

}
WebMvcConfig

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LogInterceptor()).addPathPatterns("/**");
    }

logback.xml

<pattern>[%d{yyyy-MM-dd HH:mm:ss} %-5level] [%thread] [%X{requestId}] [%file:%line] - %msg%n</pattern>

相关标签: 思路 java进阶