How to collect logs in jboss related to a single request?

I am developing a Java EE web application that runs under JBoss.

I want to do the following: When a user sends an HTTP request (opening a page or through AJAX), all the logs associated with this request are collected and then stored in the database. By I mean, they are logged during the processing of the current request. The hardest part is collecting the logs associated with a single request.

I was looking for this solution:

JBoss uses log4j for logging. When the application starts, the start listener registers the log4j application, which collects all the logs in the ThreadLocal field. At the end of the request processing, the logs are taken from the field and stored in the database.

But now it seems that log4j applications are running in other threads. This makes this decision impossible.

Do you have any ideas how to do this?

Thank you Artem B.

+3
source share
1 answer

You can use the log4j MDC class (Mapped Diagnostic Context) to associate certain data with the current stream.

I often use this to add a session identifier to the output log for any logging for this session:

public class AddSessionIdToLogFilter implements Filter {

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException,
            ServletException {

            if (request instanceof HttpServletRequest) {
                HttpServletRequest httpRequest = (HttpServletRequest) request;
                String sessionID = httpRequest.getSession().getId();

                MDC.put("SessionID", sessionID);
            }   

            ...

Then you simply refer to the MDC by keyword in PatternLayout. You do not know how the DB application works, but I assume that it can also register MDC fields ...

log4j.appender.LOGFILE.layout.ConversionPattern= ... [SessionID=%X{SessionID}] ...
+7
source

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


All Articles