Organize logs using MDC

MDC (Mapped Diagnostic Context) is supported by log4j, log4j2, and SL4J/logback and offers a key/value possibility to enrich log statements:

public class MDC {
//Put a context value as identified by key
//into the current thread's context map.
public static void put(String key, String val);
//Get the context identified by the key parameter.
public static String get(String key);
//Remove the context identified by the key parameter.
public static void remove(String key);
//Clear all entries in the MDC.
public static void clear();
}

Add an aspect (filter/interceptor etc.) to pre-handle your requests and add the desired information:

MDC.put("userId", userId);
MDC.put("correlcationId", correlationId);

In the log appender, the values can be retrieved using %X{<key>}

log4j.appender.rollingFile.layout.ConversionPattern=[%d{dd/MM/yyyy HH:mm:ss:SSS zzz}] %t %c{1} [%p] %m %X{correlationId} %X{userId} %n