通常,项目当中会添加各种各样的日志,为了方便用户请求流程的跟踪,需要每条日志上添加用户id,reqId等信息。但是通过函数参数的方式传递会比较繁琐,Slf4j为我们提供了一套简洁的处理方案。
一、通过添加Filter实例,在http请求到来时解析用户id和reqId,并将信息保存到Slf4j的MDC中,MDC会将信息保存到当前线程的context map当中;
//创建过滤器,从http头中获取用户id和reqId等信息
@Order(Ordered.HIGHEST_PRECEDENCE)
public class TraceFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain)throws ServletException, IOException {
try {
String uid = request.getHeader("UID");
String device = request.getHeader("DEVICE");
String reqId = request.getHeader("REQUEST-ID");
MDC.put("reqId", reqId);
MDC.put("uid", uid);
MDC.put("device", device);
filterChain.doFilter(request, response);
} finally {
MDC.clear();
}
}
}
//将过滤器添加到servlet的过滤器链当中
@Configuration
public class WebFilterRegistration {
@Bean
public FilterRegistrationBeanregisterFilter() {
FilterRegistrationBean filterRegistrationBean =new FilterRegistrationBean();
filterRegistrationBean.setFilter(new TraceFilter());
filterRegistrationBean.addUrlPatterns("/*");
return filterRegistrationBean;
}
}
二、设置log4j的日志格式,注意,日志格式里面的名称与放入MDC中的信息的名称保持一致
<Console name="LogToConsole" target="SYSTEM_OUT">
pattern="%d %p %c{1.} [%t] [traceId: %X{reqId} ] [userId: %X{uid} ] [device: %X{device} ] %m%n"/>
</Console>
三、在需要打印日志的类上添加@Slf4j注解,就可以使用log.info,error和warn打印带有用户id和reqId信息的日志了。
@Slf4j
public class LogTest {
public static void main(String[] args) {
MDC.put("uid", "1111");
MDC.put("reqId", "xxxxx");
MDC.put("device", "2222222");
log.info("==========================");
System.out.println("++++++++++++++++++");
}
}
日志如下:
2020-12-31 17:56:27,817 INFO c.m.s.LogTest [main] [traceId: xxxxx ] [userId: 1111 ] [device: 2222222 ] ==========================
++++++++++++++++++
网友评论