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

Bravo picture Bravo · Oct 4, 2017 · Viewed 13.4k times · Source

We are using:

  • Spring Boot
  • Slf4J
  • Logback
  • ELK stack

Now we want to use MDC to add the unique tracking number, which is provided in the POST request JSON, to every log statement for a given request.

I googled some blog posts, those are not useful for me much.

Below is the logback.xml which we are using

<configuration>
    <property name="PROJECT_ID" value="template-api"/>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="net.logstash.logback.encoder.LogstashEncoder"/>
    </appender>

    <root level="INFO">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>

Can anyone provide some help on how to get this done please?

Answer

DmitriyS picture DmitriyS · Dec 1, 2019

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");
        }
    }
}