giovedì 24 maggio 2012

Log user info with log4j on Spring + JSF webapp

You can easily log information about the logged user in a Spring + JSF web application by using a simple Servlet filter and log4j MDC Mapped Diagnostic Context.
This can be useful when you have to debug a web application where logs from different users are interwined.

I have created a small example, you could check it out with:

svn checkout http://lbonacina-experiments.googlecode.com/svn/trunk/SpringAuth spring-auth-read-only

It is a simple Web Application build with Spring 3.1 + Spring Authentication + JSF 2 + H2 in-memory DB; there is a login JSP page and a couple of JSF pages with some backing beas actions. There is also a Servlet Filter, it just gets information from the SecurityContext (the logged User) and add a small info (the logged User id) to the log4j MDC.

public class LogLoggedUserFilter implements Filter {

    protected Logger log = Logger.getLogger(this.getClass().getName());
    
    @Override
    public void destroy() {
    }

    @Override
    public void init(FilterConfig fc) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest sr, ServletResponse sr1, FilterChain fc) throws IOException, ServletException {

        SecurityContext sc = SecurityContextHolder.getContext();
        if (sc != null) {
            User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            MDC.put("lu", user.getId());
        }
        
        fc.doFilter(sr, sr1);
    }


on the log4j ConversionPatter the pattern [%X{lu}] print out the info ('lu' is the key added to the MDC) between square brackets:

log4j.appender.logfile.layout.ConversionPattern=%d{HH:mm:ss} %-5p [%X{lu}] - %-30.30c{1} - %m%n

 if necessary a simple post processing could extract from the log the entries of a single user to simplify the debugging/tracing

0 Commenti:

Posta un commento

Iscriviti a Commenti sul post [Atom]

<< Home page