Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert the username into MDC for the entire web request

I am trying to use a Mapped Diagnostic Context to add the username of the user making a page request to all relevant logging statements. However I have tried three different ways to make it work without success:

  1. Pushing the username into the MDC after login and removing after logout. This method ends up mixing up which logging statement came from which user.
  2. Using a ServletFilter to push the username into the MDC on each page load and pop it back off as the request ends. This only catches some of the data and only in Spring security layer.
  3. Using a AOP @Around interceptor in front of all the Controller methods flat out didn't work.

Does anyone have any suggestions on how to make this happen?

like image 852
chotchki Avatar asked Dec 11 '25 11:12

chotchki


1 Answers

What were the problems with MDC? What do you mean by Spring security layer? I used this approach in one web application and it worked well. Because MDC is bound to thread, all logging statements coming from this thread will have username set, i.e. service and repository layer as well.

Of course if some users are served from using threads (e.g. servlet 3.0 asynchronous processing, JMS listeners, executors), you will need the other way of injecting username to MDC in pooled threads.

Also see my answer here.

like image 152
Tomasz Nurkiewicz Avatar answered Dec 14 '25 08:12

Tomasz Nurkiewicz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!