slf4j-添加traceid

slf4j-添加traceid

起男 320 2023-10-25

slf4j-添加traceid

在日志输出中添加traceid,以方便观察一系列日志是否属于一次请求
利用拦截器和aop都可用轻松实现此功能,当然也可以根据具体业务需求将制定的值放入日志输出中

添加拦截器

public class TraceInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        MDC.put("traceid", UUID.randomUUID().toString());
        return super.preHandle(request, response, handler);
    }

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

修改配置文件

使用%X{traceid}的格式,将自定义的变量放入日志输出

		<!-- 将日志输出到控制台-->
        <Console name="CONSOLE" target="SYSTEM_OUT">
            <!--设置日志格式及颜色-->
            <PatternLayout
                    pattern="[%X{traceid}] [%style{%d}{bright,green}][%highlight{%p}][%style{%t}{bright,blue}][%style{%C}{bright,yellow}]: %msg%n%style{%throwable}{red}"
                    disableAnsi="false" noConsoleNoAnsi="false"/>
        </Console>