Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use MDC logging with Java

I have tried to find out a way of using MDC in reactive/event based async programming in java but I could not find one.

Could someone explain how to propagate MDC variables in call back events/methods?

In this case, how a request can be traced until a response is served like in traditional Synchronous programming?

like image 892
mac Avatar asked Nov 07 '22 01:11

mac


1 Answers

Programmatically you can do

MDC.put("transId", transId);

Where the transId variable holds the transaction ID you want to be able to track.

followed by this logback config:

<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
        <pattern>[%date] %level [%mdc{transId}] %m%n</pattern>
    </encoder>
</appender>

Be aware that MDC uses threadLocal to store context, so if you jump server or thread (using worker pattern for instance) you will have to reset the MDC context in the new thread. I suppose that might be what you are really asking, but there is no shortcut to keep MDC context across a thread change. This means that you will have to send your transId as a parameter in both calls and call-backs.

Annotations and AOP can alleviate some of the drudgery of transferring the transId in calls.

like image 63
Jan Larsen Avatar answered Nov 14 '22 18:11

Jan Larsen