I know this question has been asked countless times, and some instances are indeed popular, however, I still haven’t found an answer that encompasses all of the requirements that I have, which in my opinion are very common.
I essentially just want to log every web request and its corresponding response together with contextual information, like the logged-in user. I also want to log everything that happens during the processing of said request, again, with this contextual info.
The correlation of logs is done by maintaining the Mapped Diagnostic Context (MDC) with things like the user id, endpoint, parameters etc. Most online guides suggest maintaining this context via MVC Filters
(like auth. filters), or HandlerInterceptor
s. This works fine until an exception occurs, which causes some component in the stack to internally create a new “fake” request that usually points to some kind of error page. This request re-triggers all of the filters/interceptors and, due to it looking completely differently than the original request, makes correlating them very hard.
I’ll list out things that I’ve tried and tell you why they didn’t work:
HandlerInterceptor
with if-statements: I gave up on this one because I’m not sure how I can cover each exception case. For example, sometimes theException
argument inafterCompletion
is set, and sometimes not. You could be in the first or the second request round etc.@ControllerAdvice
exception handler: This indeed works, however I’d have to re-implement all of the automatic HTTP error conversion that Spring does in the background. An example of this is returning code 400 onBindException
.- Custom
DispatcherServlet
: This was suggested by a bounty-awarded answer in the above-linked question, however it also seems to get triggered twice, as the request is re-written. ServletRequestListener
: Can be used to clear the MDC, but I don’t have access to the response object.
One more thing to add is that I still don’t know if this request re-writing happens across multiple threads.