Junior — Middle
What actions can be taken to add a unique trace identifier to log entries?
sobes.tech AI
Answer from AI
To add a unique trace ID to logs in Java, you can use the following approaches:
-
Using MDC (Mapped Diagnostic Context) from logging libraries like Log4j or SLF4J. MDC allows attaching contextual data (like trace ID) to the current thread, which is automatically included in log messages.
-
Generating a unique ID at the start of request processing (e.g., UUID) and storing it in MDC.
-
Configuring the logging pattern to output the trace ID from MDC in each log entry.
Example using SLF4J and Logback:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import java.util.UUID;
public class Example {
private static final Logger logger = LoggerFactory.getLogger(Example.class);
public void processRequest() {
String traceId = UUID.randomUUID().toString();
MDC.put("traceId", traceId);
logger.info("Starting request processing");
// ... processing logic
logger.info("Finishing request processing");
MDC.clear();
}
}
In the logger configuration, add %X{traceId} in the pattern to display the trace ID in logs.