本次讲解非微服务日志链路追踪,下一篇文章在介绍微服务链路追踪
日志链路追踪主要用于定位请求日志
TraceID:TraceID标记了 浏览器发起的某个请求, 这个TraceID可在服务端从接收请求到 响应请求中流转,甚至接力传递给下游应用中流转,用于唯一标记和定外这次请求。
第一步:创建一个springboot项目
创建一个过滤器,主要生成TraceID和销毁TraceID
代码如图所示:
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import java.util.UUID;
@Component
@Order(1)
@WebFilter(urlPatterns = "/*", filterName = "logMdcFilter")
public class LogMdcFilter implements Filter {
private static final String UNIQUE_ID = "traceId";
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
boolean bInsertMDC = insertMDC();
try {
chain.doFilter(request, response);
} finally {
if(bInsertMDC) {
MDC.remove(UNIQUE_ID);
}
}
}
@Override
public void destroy() {
}
private boolean insertMDC() {
UUID uuid = UUID.randomUUID();
String uniqueId = uuid.toString().replace("-", "");
MDC.put(UNIQUE_ID, uniqueId);
System.out.println("-----traceId-----"+ uniqueId);
return true;
}
}
第二步:在resource下创建logback-spring.xml文件,添加 [%X{traceId}] 即可
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<contextName>febs</contextName>
<property name="log.path" value="D://mnt/log/server_log/docker/eureka"/>
<property name="log.maxHistory" value="15"/>
<propert