logback-MDC日志唯一标识

自定义LogbackFilter:

import org.slf4j.MDC;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import java.util.UUID; @WebFilter(filterName = "logbackFilter", urlPatterns = "/*")
public class LogbackFilter implements Filter { @Override
public void init(FilterConfig filterConfig) throws ServletException {
} @Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
UUID uuid = UUID.randomUUID();
MDC.put("wtraceid", uuid.toString().replace("-",""));
try {
filterChain.doFilter(servletRequest,servletResponse);
}finally {
MDC.remove("wtraceid");//保证一次请求一个唯一标识
}
} @Override
public void destroy() {
}
}

logback.xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml" /> <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{yyyy-MM-dd HH:mm:ss.SSS}] WTraceId[%X{wtraceid}] [%highlight(%5p)] %msg%n</pattern>
<charset>utf8</charset>
</encoder>
</appender> <root level="INFO">
<appender-ref ref="CONSOLE" />
</root>
</configuration>

tips:

1,自定义 LogbackFilter 需要实现 Filter

springboot方式需要在 LogbackFilter 类加上@WebFilter(filterName = "logbackFilter", urlPatterns = "/*")注解

启动类 ApplicationBootstrap 加上@ServletComponentScan注解

2,WTraceId[%cyan(%X{wtraceid})] 自定义wtraceid的颜色

上一篇:python面向对象之封装


下一篇:(转)SQL Server创建索引