Logback logging with MDC

In this tutorial we will provide an example of how to setup Logback logging with MDC for a Java application using SLF4J.

What is MDC?

MDC stands for Mapped Diagnostic Contexts, it is a non-intrusive way to add some context to your logging so its easier for you to diagnose an issue. For example when multiple users request information from a given web resource, each request will be serviced by a thread. As a result multiple users will log the same information to the same log file hence following a particular request journey will be quite difficult.

This is the scenario where MDC is most useful as It allows you to add information about a request which will be included in your log statements. Below is an example highlighting how to use MDC.

Logback logging with MDC

For this example you will need to include the following maven dependancies:

You will require a logback.xml file with %X included in your pattern (example shown below). The loback.xml file needs to be placed in your classpath., normally this is under the /resources directory.

Below is a simple class showing how to use MDC. When using MDC you want to add information which will be useful while processing a request such as user-id, transaction-id event-type etc… Once the request has been processed you will want to clear the MDC map.

Running the above code will produce the following log output

As you can see from the log output, the MDC map is printed in the log statement which is very useful when tracking a users request from start to finish (i.e. by using a transaction-id)

Similar posts:

  1. Java 8 Stream groupingBy examples
  2. Java 9 JShell Basics
  3. Java 8 Streams flatmap examples
  4. How to convert JSON string to Java object

References:

  1. Logback MDC Documentation
  2. SLF4J Documentation

Leave a Reply

Your email address will not be published. Required fields are marked *