Java MDCInsertingServletFilter-class And Method Code Example


Here's an example of how to use the MDCInsertingServletFilter class from the Logback library to insert information from the servlet request into the Mapped Diagnostic Context (MDC) so that it can be included in log statements:

import ch.qos.logback.classic.helpers.MDCInsertingServletFilter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;

public class MyMDCInsertingServletFilter extends MDCInsertingServletFilter {

  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
    super.init(filterConfig);

    // Insert additional information into the MDC
    MDC.put("customKey", "customValue");
  }
}

To use the filter, you will need to add it to your web application's web.xml file:

<filter>
  <filter-name>MDCInsertingServletFilter</filter-name>
  <filter-class>com.example.MyMDCInsertingServletFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>MDCInsertingServletFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

This will cause the filter to be applied to all requests to the web application. When a request is made, the filter will insert the request's remote host, request URI, and query string into the MDC, as well as any additional information that you have added in the init method.

It's important to mention that this is just one example of how the MDCInsertingServletFilter can be used, but can be customize to your needs.