Entries tagged [ndc]

You're viewing entries tagged [ndc] in the weblog safari.

Log4jSessionFilter

Preliminary information

Log4J allows to attach information to the current thread. Log4J calls this NDC. NDC stands for "Nested Diagnostic Context".

Tested Environment

  • Java 1.4 /1.5
  • Log4j 1.2.x
  • Servlet API 2.3/2.4

Instructions

1. To include in every log message the current session-ID add a ServletFilter which attachs the session-ID to the NDC

public class Log4JFilter implements Filter {

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

        String contextInformation = "";

        if (request instanceof HttpServletRequest) {
            HttpServletRequest httpRequest = (HttpServletRequest)request;
            contextInformation += httpRequest.getSession().getId();
        }

        // push information
        NDC.push(contextInformation);

        try {
            chain.doFilter(request, response);
        } finally {
            // clean up NDC
            NDC.remove();
        }
    }
}

2. Enable the filter in web.xml

  <filter>
    <filter-name>Log4JFilter</filter-name>
    <display-name>Log4JFilter</display-name>
    <description>Intercepting Filter that provides Log4J context information</description>
    <filter-class>Log4JFilter </filter-class>
  </filter>

  <filter-mapping>
    <filter-name>Log4JContextFilter</filter-name>
    <url-pattern>*.do</url-pattern>
  </filter-mapping>

3. Add the context information to the log4j-Pattern. Relevant to NDC is "%x".

   <param name="ConversionPattern" value="%d [%x] %-5p %c - %m"/>

Resulting logfile

2006-05-26 17:02:45,171 [R0rhSjqecO1gSGBDjj9omt] INFO com.Foo - bar() has been called 

Posted on by Peter Eichenauer
Tags: java log4j ndc