Image copied from https://developpaper.com/a-simple-implementation-of-java-service-call-process-tracing/

Mapped Diagnostic Context (MDC) provides a way to enrich log messages with information that could be unavailable at the place where logging actually occurs but can be indeed useful for better tracking of program flow.

Why use MDC

Let’s assume that we have to write software that downloads receipts for given order event.

To perform download, we need to make a simple API call

The main issue to note here is that when the log message is created, it’s not possible to access orderId or traceId, only receiptId is accessible.

Now, if we use this code to fetch receipt for multiple order event parallelly, it will be very hard to map between order event and receipt using logs.

How to use MDC

We can make use of log4js to log structured message with MDC.

To be able to configure MDC, we need to first configure log4js to print message in JSON format. Same can be achieved by following code

Once log are getting printed in JSON format, we can make use log.addContext() method to add metadata which can be used for tracking.

Now, logs will be in JSON format, also it’ll have required metadata.

Note: context will be printed in the logs automatically as you can see in the following image

As you can see in the above image, all the logs have corresponding orderId and traceId, therefor if we faced any issue, we will be easily map log message with particular order event.

MDC has lot of application, mainly in scenarios of asynchronous/parallel processing caused interleaved messages.

PS: I hope you’ve enjoyed it, and if you’ve found it useful, please feel free to share with others or leave a comment 😃. Incase you want to check the entire file, you can check it here.

Originally posted on medium.com.