ammerzon
ammerzon

Reputation: 1078

Log4jNestedDiagnosticContextFilter for Log4j 2

As of Spring 4.2.1 the Log4jNestedDiagnosticContextFilter is deprecated following Apache's EOL declaration for log4j 1.x as seen below.

enter image description here

I have found the corresponding JIRA Ticket (SPR-13400) but how can I bring Log4j 2 into the Spring environment to do the same as the Log4jNestedDiagnosticContextFilter?

Upvotes: 4

Views: 432

Answers (1)

ammerzon
ammerzon

Reputation: 1078

I implemented it myself by copying the Log4jNestedDiagnosticContextFilter and adapt the logger to Log4j 2 and change NDC to ThreadContext.

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.ThreadContext;
import org.springframework.web.filter.AbstractRequestLoggingFilter;

import javax.servlet.http.HttpServletRequest;

public class CustomRequestLoggingFilter extends AbstractRequestLoggingFilter {

  protected final Logger log4jLogger = LogManager.getLogger(getClass());

  @Override
  protected void beforeRequest(HttpServletRequest request, String message) {
    if (log4jLogger.isDebugEnabled()) {
      log4jLogger.debug(message);
    }
    ThreadContext.push(getNestedDiagnosticContextMessage(request));
  }

  @Override
  protected void afterRequest(HttpServletRequest request, String message) {
    ThreadContext.pop();
    if (ThreadContext.getDepth() == 0) {
      ThreadContext.removeStack();
    }
    if (log4jLogger.isDebugEnabled()) {
      log4jLogger.debug(message);
    }
  }

  protected String getNestedDiagnosticContextMessage(HttpServletRequest request) {
    return createMessage(request, "", "");
  }
}

Upvotes: 2

Related Questions