简体   繁体   中英

MDC logging wrong session ID in log files

We are using MDC to log all transactions with session Id , but sometimes it appends the wrong sessiond

Iam sessting the sessionId in Filter

MDC.put("sessionId", request.getSession().getId());

Log Output

2015-01-24 23:13:04,857 INFO [STDOUT] (http-0.0.0.0-8090-28) [LOGBACK] 23:13:04.857 [INFO ] 371691C0B3B4481E9589BDE0C24F54C8 [Inbound Message][ID:319526][Address:http://195.233.91.82:8090/myacct/activate/updateConsent][Http-Method:POST][Content-Type:application/json; charset=UTF-8][Headers:{cookie=[JSESSIONID=371691C0B3B4481E9589BDE0C24F54C8;.....
2015-01-24 23:13:05,242 INFO [STDOUT] (http-0.0.0.0-8090-28) [LOGBACK] 23:13:05.242 [INFO ] 1434BC692D5059660EA0F8B36B143064 [Outbound Message][ID:319526][Response-Code:200][Content-Type:application/json;charset=utf-8].......

As you can see when the request the revived the sessionId was correct and when when the response is logged wrong sessionId was appended but the thread is same for both logs.

As per MDC "The MDC is managed on a per thread basis"

Is there anything wrong I am doing ?

Quoting from the source:

https://blog.trifork.com/2013/06/06/adding-user-info-to-log-entries-in-a-multi-user-app-using-mapped-diagnostic-context/

Consequences of MDC being ThreadLocal-based

Before the thread is reused to process another request, you should remove the entries you put in there so that they're not inadvertently picked up by the next user of the thread. It's usually best to do this in a finally clause as shown in the above example, so that cleanup happens even in the event of an exception being thrown.

Propagating MDC contents to other threads happens automatically for child threads (UPDATE: this not true anymore for Logback starting with version 1.1.5), but not when you're using threads obtained from eg a thread pool. That means that you lose the MDC info when you're running some asynchronous task.

If you'd like the MDC contents to be available from worker threads, then make sure that you propagate the MDC contents to those threads before running your tasks. SLF4J's MDC has a getCopyOfContextMap() method for this particular purpose. One possible approach for this is to use a dedicated Runnable subclass:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM