如何为每个log4j请求生成唯一的请求ID

时间:2017-03-29 15:21:31

标签: java logging log4j log4j2

我使用log4j打印请求和响应的日志。我想为每个请求分配一个唯一的ID,并为其响应分配相同的ID,有多个请求,因此我更容易识别每个请求和响应。

这就是我正在使用的,但它不起作用。它也会在响应时更新UDID。

    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);        
}

然后我才知道log4j提供了一种记录每个请求的唯一ID的方法。

我已经在stackoverflow上阅读了很多帖子,但仍然无法理解它。

这是我的properties个文件。

# 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

1 个答案:

答案 0 :(得分:1)

您可以考虑使用上下文地图查找,这是一个简短的示例:

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>

输出

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

我希望它有所帮助:)