If you are using spring MVC you could use an interceptor like below.
Of course you could retrieve other information (eg. username) from the
session or the request.
If your not using Spring MVC you could so something similar with a servlet
filter

http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/Filter.html

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.apache.log4j.NDC;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* This interceptor pushes the remote address in the NDC
*/
public class LogRemoteAddressInterceptor extends HandlerInterceptorAdapter {

 public boolean preHandle(HttpServletRequest request, HttpServletResponse
response, Object handler) {
   String remoteAddr = getRemoteAddress(request);
   NDC.push(remoteAddr);
   return true;
 }

 public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)  {
   NDC.pop();
 }
}

 public static String getRemoteAddress (HttpServletRequest request) {
   String remoteAddr = request.getHeader("X-Forwarded-For");
   if (remoteAddr == null)
     remoteAddr = request.getRemoteAddr();
   return remoteAddr;
 }




On 2/22/07, James Stauffer <[EMAIL PROTECTED]> wrote:

In something like a servlet engine one thread usually handles one user
request until that request is done.  Then you can set the username in
the MDC and it will be logged correctly.  How is your application
different?  Does one thread handle multiple users at the same time?

On 2/21/07, Sriram Sundararajan <[EMAIL PROTECTED]> wrote:
> Hi,
>      I am using Log4j for a web oriented project, where i have to log
the
> messages with logged in user id and his name.
>     Each and every time i don't want to pass the userid and username
from
> the session like below.
>     logger.debug("<userid>","<username>","<messages.....>");//i don't
want
> to do this
>
>    I want to use something similar to below statement. But in the log
file i
> have to see the userid and user name
>
>     logger.debug("<messages.....>");//i want to do this
>
>   I tried to use MDC and NDC, but for each and every call i need to set
this
> value before making a call....
>    MDC.put("userid',<....>);
>    MDC.put("username',<....>);
>
>  Only for one time i want to set this value, after that i don't want to
do
> that. If you know any design patterns for this it will be of great help.
>
> regards
> sri
>


--
James Stauffer        http://www.geocities.com/stauffer_james/
Are you good? Take the test at http://www.livingwaters.com/good/

---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]


Reply via email to