Thursday, 19 April 2012

AS7 Seam2 LoggingFilter

Seam2 allows us to add user name to each server log entry triggered by that user. This is described id "Identity Logging" chapter. We only need to enable logging-filter in components.xml and add %X{username} to log pattern.

But what if we want more, like IP ?

Add org.jboss.logmanager to jboss-deployment
Add AS7LoggingFilter
 * This filter adds user IP to the log4j
 * mapped diagnostic context so that it can be included in
 * formatted log output if desired, by adding %X{ip}
 * to the pattern.
 * @author Bernard Labno
@Filter(within = "org.jboss.seam.web.authenticationFilter")
@Install(classDependencies = "org.jboss.logmanager.Logger",
    dependencies = "",
    precedence = Install.BUILT_IN)
public class AS7LoggingFilter extends AbstractFilter {
// ------------------------ INTERFACE METHODS ------------------------

// --------------------- Interface Filter ---------------------

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
        HttpSession session = ((HttpServletRequest) servletRequest).getSession(false);
        if (session != null) {
            Object attribute = session.getAttribute("");
            if (attribute instanceof Identity) {
                Identity identity = (Identity) attribute;
                Credentials credentials = identity.getCredentials();
                String username = credentials != null ? credentials.getUsername() : null;
                if (username != null) {
                    MDC.put("username", username);
        MDC.put("ip", servletRequest.getRemoteAddr());
        filterChain.doFilter(servletRequest, servletResponse);
Modify POM dependency log4j-api to provided scope
Modify pattern in standalone.xml or domain.xml by adding %X{ip}, i.e.:
    <pattern-formatter pattern="%d{HH:mm:ss,SSS} %-5p [%c] (%t) %X{ip} %X{username} %s%E%n"/>

Try %X{hostname} but it may not work with proxy.