简体   繁体   中英

How to generate unique request id for each log4j request

I am printing log of request and response by using log4j. I want to assign a unique ID to each request and same ID to its response, there are multiple requests so it will be easier for me to identify each request and response.

This is what i was using, but its not working. Its updating the UDID on response as well.

    public void logRequestObject(HttpServletRequest httprequest){
    uniqueID= UUID.randomUUID().toString();          
    logger.info("Log4J - "+ "Request: requestId= "+ uniqueID+  ",Headers= "+ map);  
}

    public void logResponseObject(HttpServletResponse httpResponse){    
      logger.info("Log4J - "+ "Response: ,requestId= " + uniqueID + " ,responseTime= " + " totalTime= "+ totalTime);        
}

Then i came to know that log4j provides a way to record unique ID to each request.

I have read many posts on stackoverflow, but still unable to understand it.

This is my properties files.

# Root logger option
log4j.rootLogger=INFO, stdout, file, CATALINA

# Catalina

    log4j.appender.CATALINA=org.apache.log4j.RollingFileAppender
    log4j.appender.CATALINA.File=${catalina.home}/logs/catalina.out
    log4j.appender.CATALINA.MaxFileSize=10MB
    log4j.appender.CATALINA.MaxBackupIndex=5
    log4j.appender.CATALINA.layout=org.apache.log4j.PatternLayout
    log4j.appender.CATALINA.layout.ConversionPattern=%d{dd.MM.yyyy HH:mm:ss}  %X{RequestId} %p-%c{1}: [%m]%n
    log4j.appender.CATALINA.Append=true
    log4j.appender.CATALINA.Encoding=UTF-8

You can consider using Context Map Lookup , here's a brief example:

Java code sinppet:

public static void main(String[] args) {
  String uuid = "1";
  logRequestObject("http request", uuid);
  logResponseObject("http response");

  uuid = "2";
  logRequestObject("http request", uuid);
  logResponseObject("http response");
}

static void logRequestObject(Object httpRequest, String uniqueID) {
  ThreadContext.put("uniqueID", uniqueID); // Update uniqueID before logging request and response
  logger.info("This is {}", httpRequest);
}

static void logResponseObject(Object httpResponse) {
  logger.info("This is {}", httpResponse);
}

log4j.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
    <Appenders>
        <Console name="STDOUT" target="SYSTEM_OUT">
            <PatternLayout pattern='%level -> %msg %X{uniqueID}%n'/> <!-- Get uniqueID from ThreadContext -->
        </Console>
    </Appenders>

    <Loggers>
        <Root level="DEBUG">
            <AppenderRef ref="STDOUT"/>
        </Root>
    </Loggers>
</Configuration>

Output

INFO -> This is http request 1
INFO -> This is http response 1
INFO -> This is http request 2
INFO -> This is http response 2

I hope it helps :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM