――In batch processing, I want to quickly search where the same processing log is from when parallel processing or continuous processing is performed. -Write on the assumption that @ Slf4j is used
--In Java class, register the information you want to output to the log using MDC (MDC.put)
--At the end, remove the key with remove
--You can get the key registered in MDC in logback.xml in the format of % X {<key>}
.
logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE logback>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>traceID: [%X{traceId}] message: %msg%n</pattern>
</encoder>
</appender>
<root>
<appender-ref ref="STDOUT" />
</root>
</configuration>
import java.util.UUID;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
@Slf4j
public class Traceid {
public static void main(String[] args) {
log.info("dummy1");
String uuid = UUID.randomUUID().toString();
MDC.put("traceId", uuid.substring(0, uuid.indexOf("-")));
log.info("dummy2");
MDC.remove("traceId");
log.info("dummy3");
}
}
Console log
traceID: [] message: dummy1
traceID: [4f9c9243] message: dummy2
traceID: [] message: dummy3
Since MDC.put is a static method, why not use the same value when using it in multiple threads? → Since the Map where MDC stores the key is stored in ThreadLocal, there is no need to worry about using the same value between threads!
Recommended Posts