filterstruts2slf4jlog4j2struts2-interceptors

Log4j (SLF4J) MDC Context in Struts 2 Interceptor


I find that one can set the Log4j (SL4J) MDC context in a thread safe way in a general filter (Code from Adding user info to log entries in a multi-user app using Mapped Diagnostic Context)

import org.slf4j.MDC;
import javax.servlet.*;
import java.io.IOException;
 
public class MDCFilter implements Filter {
 
  @Override
  public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
          throws IOException, ServletException {
      User user= (User) session.getAttribute("USerSession");
      MDC.put("userName", user.getUserName() );
    try {
      chain.doFilter(req, resp);
    } finally {
        MDC.remove("userName");
    }
  }
 
}

Can I do the same approach in the Struts 2 interceptor ?! What I wonder is thread safty issues.

Struts 2 interceptor and servlet filters are not both thread safe and MDC implementation is thread safe, so if above code works fine in a filter, theoretically it must be work thread safe in the interceptor.

Any comments ?!


Solution

  • Interceptors are not thread safe means that you have to write them in thread safe manner. For example below interceptor is thread safe.

    public class LoggerInterceptor extends AbstractInterceptor {
      @Override
      public String intercept(ActionInvocation invocation) throws Exception {
        HttpSession session = ServletActionContext.getRequest().getSession();
        User user= (User) session.getAttribute("USerSession");
        MDC.put("userName", user.getUserName() );
        String result;
        try {
          result = invocation.invoke();
        } finally {
          MDC.remove("userName");
        }
        return result;
      }
    }