Member-only story

Spring Boot

Improve Logging Using MDC

How to use MDC in spring boot and some best practices

Fahim Fahad
JavaToDev
Published in
3 min readJul 12, 2022

--

We use logging in our projects to better understand the system. With proper logging, we can easily track down the issues. Using MDC (Mapped Diagnostic Context), we can improve logging. In this article, I will explain how we can use MDC and will provide a list of best practices for logging.

Photo by Jake Walker on Unsplash

If you are not a member, you can read here

Configure MDC

Now I will configure my spring boot application to use MDC for logging user specific data. I will use web filter to set user id in the MDC.

Normally, we can validate user authentication in the web filter. So we’ll have user data like id, session id, token validity, and so on. We must exercise caution when setting data into MDC. We should not store sensitive information there. In addition, once the request is complete, we must clear the data from MDC. Because MDC implementation uses ThreadLocal, it is possible that the same thread will serve other requests. If we do not clear MDC data after each execution, we may get an incorrect log.

Now we need to configure our log pattern (console and file) to use this data during logging.

I have added a logback-spring.xml file in the project. In the console and file log pattern I used a variable userId that I added in the MDC.

I uploaded the sample code in this branch: https://github.com/olein/Java-AWS-RnD/tree/MDC

All done. Now every log will print userId and we will be able to isolate each user log.

Logging best practices

  1. PII should not be logged.

--

--

JavaToDev
JavaToDev

Published in JavaToDev

We write about Spring Boot, Java, Microservices, and More Interesting Topics inside Java Ecosystem.

Fahim Fahad
Fahim Fahad

Responses (1)

Write a response