Home > Enterprise >  How to identify and log simultaneous api requests?
How to identify and log simultaneous api requests?

Time:11-20

I developed a Rest API with some logs (requests, responses, more info and errors)

I saw that if there are simultaneous requests, logs mix and you cant follow the execution in logs because you dont know which request was used for that log line.

Is there any execution id that can be added at the beginning of every log line so I can follow the execution of that request?.

I'm using Log4j

CodePudding user response:

You can include information about the thread by using the properties %tid (thread id) and %tn (thread name). I'll show a modified example from https://www.codingame.com/playgrounds/4497/configuring-logback-with-spring-boot:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

  <appender name="STDOUT" >
    <encoder>
      <pattern>
        %d{dd-MM-yyyy HH:mm:ss.SSS} %tid %tn %magenta([%thread]) %highlight(%-5level) %logger{36}.%M - %msg%n
      </pattern>
    </encoder>
  </appender>

  <root level="info">
    <appender-ref ref="STDOUT"/>
  </root>
 
</configuration>

CodePudding user response:

Solved, what I was looking for was for a Request ID, not Thread Id.

public class LoginServide implements ServletRequestListener{
    public void requestInitialized(ServletRequestEvent arg0){
        MDC.put("RequestID", UUID.randomUUID());
    }
    public void requestDestroyed(){
        MDC.clear(); 
    }
}

in .properties

log4j.appender.app.layout.ConversionPattern= %X{RequestID} ...

now I can see the requestID in every log line, so I can follow it even though if log is mixed for simultaneous requests

  • Related