Logging additional information like SessionID in every Log4j message

In his blog posts Log4j MDC (Mapped Diagnostic Context) : What and Why and Log4j MDC (Mapped Diagnostic Context) : Example code, Veera Sundar explains the concept of the Mapped Diagnostic Context (MDC), a thread-local key-value store that can be accessed from the Log4j conversion pattern. A common use case for the MDC is to log the user name or the sessionID of a user so that you can see in the log file what actions a user has done.

To use the MDC, you have to put a placeholder into your Log4j conversion pattern:

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

In this pattern the Variable “sessionId” in the MDC (referenced by %X) will be logged right next to the date of the log message.

To make this work, you have to put the SessionID into the MDC, using the static method MDC.put(key, value).

import org.apache.log4j.MDC;
MDC.put("sessionId", sessionId)

If you use SLF4J instead of using Log4j directly, change the import to

import org.slf4j.MDC

Because the MDC is thread-local and every request in a web application has it’s own thread, you have to put the sessionID into the MDC at the beginning of each request. You can do this by using a servlet filter.

Short URL for this post: https://blog.oio.de/WQL6R
This entry was posted in Java Basics and tagged , , , , . Bookmark the permalink.