Mapped Diagnostic Context with Logging Framework

The Mapped Diagnostic Context (MDC) is a concept, saying that it allows from the Java code, we can pass some information to the log message beside the message that we need to log using the Logging Framework such as Log4J, Log4J2, Logback, SLF4J. Using this function will help us in some cases, such as tracking the application’s performance according to certain criteria through the message log, … How it is in details, let’s learn together in this tutorial.

First, I will create a new Maven project:

Mapped Diagnostic Context with Logging Framework

and use SLF4J for Log4J as an example:

For simplicity, we will configure Log4J with simple content as follows:

Mapped Diagnostic Context with Logging Framework

With the configuration of PatternLayout above, each log message will have the format: logging level + category + message need to log + line break.

Then, if I want to log a message:

The results are as follows:

Mapped Diagnostic Context with Logging Framework

Now, if I want to identify the log message come from which user, if I do not use the Mapped Diagnostic Context, I need to add that code to every message I need to log. Eg:

Result:

Mapped Diagnostic Context with Logging Framework

If now, I use the Mapped Diagnostic Context by modifying the code using the SLF4J org.slf4j.MDC object:

and declares the user keyword to PatternLayout in Log4J’s configuration file:

The result is the same:

Mapped Diagnostic Context with Logging Framework

As you can see, using the SLF4J MDC object allows us to define a key with its value. Then, declare this key in the configuration file of Log4J with the syntax:

This helps us to pass the information we need to the log message separated from the message to the log, reducing the effort a lot.

 

5/5 - (1 vote)

Add Comment