How to use MDC of logback and SLF4J with spring boot to capture unique tracking in the POST request json?

后端 未结 2 668
轮回少年
轮回少年 2021-01-18 17:29

We are using:

  • Spring Boot
  • Slf4J
  • Logback
  • ELK stack

Now we want to use MDC to add the unique tracking num

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-18 18:14

    Sorry, don't have enough rep to write comment. This is more correct, fully working code, based on @glytching answer:

    @Component
    public class MDCFilter extends OncePerRequestFilter {
    
        @Autowired
        private TrackingnumberGenerator trackGen;
    
        @Override
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
            MDC.put("trackingNumber", trackGen.getTrackingNumber());
            try {
                filterChain.doFilter(request, response);
            } finally {
                MDC.remove("trackingNumber");
            }
        }
    }
    

提交回复
热议问题