Java HTTP User Name Log4j MDC Servlet Filter

This simple servlet filter puts the logged-in user's name into a Log4J Message Diagnostic Context. This intented to facilitate association of log entries to different (concurrent) users.

This may be used with either normal HTML-based web applications (BASIC HTTP(S) authentication), but especially with fat clients that use RMI tunneled over BASIC authenticated HTTP(S). The idea is to use the MDC as part of the Log4J (file) appender pattern, then use grep <your user name> to filter out only those lines which relate to your own current login. As far as I know, filtering based on MDC content may also be enabled on the appender level, but I have never yet configured this. Plain tail -f | grep mgr works nicely for me (Linux of course, Windows can't do tail -f).

Download

Load the Java source code file here (MDCUserServletFilter.java).

Compilation

With JBOSS_HOME set, use javac -d . -classpath $JBOSS_HOME/lib/log4j-boot/jar:$JBOSS_HOME/server/default/deploy/jbossweb-tomcat50/sar/servlet-api.jar MDCUserServletFilter.java

Installation

Update the JBoss http-invoker web application's web.xml located at $JBOSS_HOME/server/default/deploy/http-invoker/sar/invoker/war/WEB-INF/web.xml. Add a filter definition:

<filter>
  <filter-name>MDCUserServletFilter</filter-name>
  <filter-class>de/rtner/webtools/MDCUserServletFilter</filter-class>
</filter>

<filter-mapping>
  <filter-name>MDCUserServletFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

Then copy the filter class file to $JBOSS_HOME/server/default/deploy/http-invoker/sar/invoker/war/WEB-INF/classes/de/rtner/webtools/MDCUserServletFilter.class. Redeploy the HTTP invoker application or simply bounce the JBoss server.

Finally, adjust your Log4j appender to include the %X{username} substitution.

Version

This relates to JBoss 3.2.7 and Servlet Specification 2.3. Should work for all standard servlet containers as well as other application servers which offer web application-based RMI tunneling.

Caveats

A J2EE Message Driven Bean will run in a different thread than the calling JSP, of course. So if your code (JSP, SLSB, Entity Bean, whatever) passes a message to an MDB, this MDB's Log4J messages will not contain the user information of the initiating user. If this is required, the calling code must pass the user information to the MDB explicitly (as JMS message attributes, for example) and the MDB has to set the MDC based on this information.

Copyright

This class was written by me, Matthias Gärtner. This code is released under the Lesser GNU Public License (LGLP).

Back to main page. Back to software page.


 
This page was last changed on January 07th, 2006. © Matthias Gärtner 2006