This problem is handled very well by Logback . I suggest choosing it if you have freedom.
Assuming what you need, you will need SiftingAppender . It allows you to separate the log files according to some runtime value. This means that you have a wide selection of ways to split log files.
To split your files into requestId , you can do something like this:
logback.xml
<configuration> <appender name="SIFT" class="ch.qos.logback.classic.sift.SiftingAppender"> <discriminator> <key>requestId</key> <defaultValue>unknown</defaultValue> </discriminator> <sift> <appender name="FILE-${requestId}" class="ch.qos.logback.core.FileAppender"> <file>${requestId}.log</file> <append>false</append> <layout class="ch.qos.logback.classic.PatternLayout"> <pattern>%d [%thread] %level %mdc %logger{35} - %msg%n</pattern> </layout> </appender> </sift> </appender> <root level="DEBUG"> <appender-ref ref="SIFT" /> </root> </configuration>
As you can see (inside discriminator ), you will distinguish the files used to write logs to requestId . This means that each request will be sent to a file with the corresponding requestId . Therefore, if you had two requests, where requestId=1 and one request, where requestId=2 , you will have 2 log files: 1.log (2 entries) and 2.log (1 entry).
At this point, you may wonder how to install key . This is done by entering key-value pairs in MDC (note that the key matches the key defined in the logback.xml file):
RequestProcessor.java
public class RequestProcessor { private static final Logger log = LoggerFactory.getLogger(RequestProcessor.java); public void process(Request request) { MDC.put("requestId", request.getId()); log.debug("Request received: {}", request); } }
And thatβs basically it for easy use. Now, every time a request arrives with a different (not yet met) identifier, a new file will be created for it.
source share