Logging a unique ID for every request using log4j

I wanted to assign a unique ID to web requests in my application so that I could easily differentiate between different requests when looking at my logs.

My log4j conversion pattern (or format) looked like this:

%d{ISO8601} [%t] %p %c - %m%n

Explanation:

  • %d{ISO8601}: Timestamp using log4j’s ISO8601DateFormat
  • %t: Thread name
  • %p: Priority (eg DEBUG, INFO, etc)
  • %c: Category (in my code I’m using the class as category)
  • %m: Message
  • %n: Line break

I added a custom field:

%d{ISO8601} [%t] %p %c %X{requestId} - %m%n

Using my RandomIdGenerator class, I added this interceptor:

@Override
public boolean preHandle(
        HttpServletRequest request,
        HttpServletResponse response, Object handler) {
    String requestId = RandomIdGenerator.base32(4);
    MDC.put("requestId", requestId);
    return true;
}

I now get output like this in my log:

2013-06-21 10:01:49,178 [http-443-4] INFO com.boxjar.web.AuthenticationInterceptor YDXT5PI - User box authenticated successfully.
2013-06-21 10:01:49,182 [http-443-4] DEBUG com.boxjar.logic.DomainService YDXT5PIĀ - Saved changes to contract 154.

I wish everything was this easy!