Java – how to collect logs in JBoss related to a single request?

I am developing a Java EE web application running under JBoss

I want to do the following: when a user sends an HTTP request (by opening a page or through Ajax), all logs related to the request will be collected and saved to the database Relevance means that they are recorded in the process of processing the current request The hardest part is collecting logs related to individual requests

I'm working on this solution:

JBoss uses log4j for logging When the application starts, the startup listener registers a log4j appender, which collects all logs into the ThreadLocal field At the end of request processing, the log will be obtained from the field and saved to the DB

However, it now appears that log4j appender works in other threads This makes this solution impossible

What do you think and how do you do it?

Thank you, Artem B

Solution

You can use log4j MDC class (mapped diagnostic context) to associate some data with the current thread

I often use it to add the session ID to the log output for any logging of the 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 just need to press the key in patternlayout to reference MDC I'm not sure how DB appender works, but I think it can also record MDC fields

log4j.appender.LOGFILE.layout.ConversionPattern= ... [SessionID=%X{SessionID}] ...
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>