Class RequestIdHandler

All Implemented Interfaces:
ApplicationHandler<RequestHandler>, Handler<ApplicationEvent<RequestHandler>>

public class RequestIdHandler extends RequestHandler
A RequestHandler that manages a per-request correlation ID ("X-Request-ID").

On every incoming request the handler:

  1. reads the X-Request-ID HTTP header;
  2. if absent or blank, generates a short random identifier (first 8 chars of a UUID, upper-cased);
  3. if present but longer than 128 characters, truncates it;
  4. stores the value in the SLF4J MDC under the key "requestId" so that it appears in every log line of the current thread;
  5. stores the value in a thread-local so that it can be retrieved at any point via currentRequestId();
  6. echoes the value back to the client immediately via the X-Request-ID HTTP response header, before the response is committed.

On the response the handler cleans up both the MDC entry and the thread-local.

The handler is unfiltrable: it runs for every request regardless of the include/exclude rules configured in application.yaml.

Author:
Luca Frosini (ISTI-CNR)
  • Field Details

    • MDC_KEY

      public static final String MDC_KEY
      MDC key used to store the request ID in the logging context.
      See Also:
  • Constructor Details

    • RequestIdHandler

      public RequestIdHandler()
  • Method Details

    • currentRequestId

      public static String currentRequestId()
      Returns the request ID associated with the current thread, or null if none is set (i.e. the call is not going through the SmartGears request pipeline).
      Returns:
      the current request ID, or null
    • getName

      public String getName()
      Specified by:
      getName in class RequestHandler
    • isUnfiltrable

      public boolean isUnfiltrable()
      This handler must run even on paths that are excluded from other handlers so that every request gets a correlation ID in the logs.
      Overrides:
      isUnfiltrable in class RequestHandler
    • handleRequest

      public void handleRequest(RequestEvent e)
      Description copied from class: RequestHandler
      Invoked when the container receives a request for a servlet of a managed app.
      Overrides:
      handleRequest in class RequestHandler
      Parameters:
      e - the request event
    • handleResponse

      public void handleResponse(ResponseEvent e)
      Description copied from class: RequestHandler
      Invoked when a servlet of a managed app has produced a response to a request.
      Overrides:
      handleResponse in class RequestHandler
      Parameters:
      e - the response event
    • toString

      public String toString()
      Overrides:
      toString in class AbstractHandler