views:

82

answers:

1

In Seam, using log4, I would like to have my info, warn and error always logging the logged in user (if so) name to be logged with whatever the log message is.

Being a consistant thing I do not want to have to grab the logged-in user name, and prefix the message. so I attempted to populate the log4j NDC to have it as a field of the log message. Pushing the user name on successful login:

NDC.push(credentials.getUsername());

Which works, but the NDC is managed per thread, so once another thread processes a request from the same logged in user, the trace of this user name is lost. I was thinking that there should be a common pattern to accomplish this simple task which is attaching each log message to the logged user, using the NDC or not, to know exactly what user triggered what action.

Anyone knows the appropriate way to accomplish this?

+2  A: 

Seam LoggingFilter fullfil your needs

Binds the username of the authenticated user to the Log4j Mapped Diagnostic Context (MDC),a referenced using the literal pattern %X{username}

But it is enabled whether Log4j is on the classpath - org.apache.log4j.Logger - And you have an enabled Identity component - org.jboss.seam.security.identity

Here goes some piece of code of LoggingFilter

HttpSession session = ((HttpServletRequest) servletRequest).getSession(false);
if (session != null) {
   Object attribute = session.getAttribute("org.jboss.seam.security.identity");
   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);
   }
}
Arthur Ronald F D Garcia
Great thank you. I didn't realize that this is implemented by default. Seam's folks really did the job for us.
Marc