multithreadingmdcjboss-logging

Jboss logger clear MDC during thread lifecycle


I need to improve logging in a JavaEE application running on wildfly using jboss logger & logstash, I'm using MDC to store userID but as I'm new with thread usage I'm not figuring out how to clear the MDC before a thread is recycled

I have found different ways to clear the MDC but I think I am missing some pieces of knowledge regarding threads ... : I've tried to extend Thread :

public class MdcThread extends Thread {
    LoggingTools loggingTools = new LoggingTools(MdcThread.class);

    @Override
    public void run() {
        loggingTools.info("MdcThread");
        MDC.clear();
    }
}

I've tried to extend ThreadPoolExecutor :

public class MdcThreadPoolExecutor extends ThreadPoolExecutor {
    static LoggingTools loggingTools = new LoggingTools(MdcThreadPoolExecutor.class);

...constructors...

    @Override
    public void execute(Runnable command) {
        super.execute(wrap(command));
    }

    public static Runnable wrap(final Runnable runnable) {
        return new Runnable() {
            @Override
            public void run() {
                try {
                    runnable.run();
                } finally {
                    loggingTools.info("Mdc clear");
                    MDC.clear();
                }
            }
        };
    }
}

But none of these are called ... So I assume ThreadPoolExecutor is a way of using thread but not necessarily used? how can I reach the lifecycle of the threads?

EDIT : Here is the filter I've used :

@WebFilter("/*")
public class MdcFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        if (request != null) {
            //add what I want in MDC
        }

        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        MDC.clear();
    }

}

Solution

  • If you're using logback then WildFly or JBoss Log Manager will not be managing MDC. Most implementations of MDC, and I assume you're using org.slf4j.MDC since you're using logback, are thread locals so MDC.clear() will only clear the map on that threads MDC map. Have a look at slf4j's MDC manual.

    If you want to clear the message diagnostic context you need to do it in the same thread that adds that adds the data you want cleared.