Logback MDC put () modified object

I work with the Vaadin framework and it does not support event capture well, and I cannot know when the session or user interface is activated, so I cannot put their identifiers in the MDC.

Normally I would:

public void onSessionBegin(){ MDC.put("session", VaadinSession.getCurrent().toString()); //<-- String is immutable } public void onSessionEnd(){ MDC.remove("session"); } 

But I do not have such events, so I would like to:

 // in the servlet init or wherever MDC.put("session", new Object(){ public String toString() { VaadinSession.getCurrent().toString() }; }); //<-- This is mutable and will be evaluated each time 

Thus, no matter how long the session changes, in the log I will get the current one.

Is it possible? How to replace a logical MDC implementation with a regular one? Should I edit the sources of slf4j and logback?

+6
source share
1 answer

You do not want to fetch the current session from the local thread variable for each log line (which does VaadinSession.getCurrent() ). The API uses the static String type because it is the fastest.

Vaadin does have a SessionInitListener and SessionDestroyListener , but this is also not what you want: MDC is a local thread, but not all requests in one session are processed within the same thread. Therefore, you must set a value in the MDC for each request in the RequestHandler implementation. I don't think Vaadin has a callback interface to complete the request, so there seems to be no good place to clear the value.

UPDATE: after this answer was accepted, I found that there is actually a better way to set and clear the value so that if the server processes the threads for different sessions, it does not contain false information. What you need to do is subclass VaadinServlet or VaadinPortlet and override createServletService() to return a custom subclass of VaadinServletService or VaadinPortletService , which in turn overrides both requestStart() and requestEnd() to set and delete values โ€‹โ€‹to requestEnd() accordingly.

+3
source

Source: https://habr.com/ru/post/954235/


All Articles