相关文章推荐
酒量大的板栗  ·  log4j ...·  2 天前    · 
俊逸的仙人球  ·  Azure Function Proxy ...·  1 年前    · 
魁梧的灭火器  ·  SQL ...·  1 年前    · 

log4j.properties

log4j.rootLogger=info, stdout, R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] [%X{TRACE_ID}] (%F:%L) - %m%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=example.log
log4j.appender.R.MaxFileSize=100KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n

单方法调用

@Slf4j
public class MDCDemo {
    private static final String TRACE_ID = "TRACE_ID";
    @Test
    public void testMdc1() {
        MDC.put(TRACE_ID, UUID.randomUUID().toString());
        log.info("log in main method");

输出日志:

INFO [main] [f6bbd26d-2620-4167-887c-993dbc529221] (MDCDemo.java:22) - log in main method

可以看到,我们配置的TRACE_ID已经输出来了

@Slf4j
public class MDCDemo {
    private static final String TRACE_ID = "TRACE_ID";
    @Test
    public void testMdc2() {
        MDC.put(TRACE_ID, UUID.randomUUID().toString());
        log.info("log in main method");
        nestMethod();
    private void nestMethod() {
        log.info("log in nest method");

输出日志:

INFO [main] [33cc07fc-8fdd-4f0c-9a6c-fd60cadf1f66] (MDCDemo.java:28) - log in main method
INFO [main] [33cc07fc-8fdd-4f0c-9a6c-fd60cadf1f66] (MDCDemo.java:33) - log in nest method

可以看到,主方法和嵌套方法里的TRACE_ID是一样的

多线程调用

@Slf4j
public class MDCDemo {
    private static final String TRACE_ID = "TRACE_ID";
    @Test
    public void testMdc3() throws IOException {
        new Thread(() -> {
            MDC.put(TRACE_ID, UUID.randomUUID().toString());
            log.info("log in thread1 start");
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            log.info("log in thread1 end");
        }).start();
        new Thread(() -> {
            MDC.put(TRACE_ID, UUID.randomUUID().toString());
            log.info("log in thread2 start");
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            log.info("log in thread2 end");
        }).start();
        System.in.read();

输出日志:

INFO [Thread-0] [77011a2b-d5ec-4846-8a0b-0177be25464c] (MDCDemo.java:40) - log in thread1 start
INFO [Thread-1] [ceace569-f862-41b6-97b6-0ed9561df5c3] (MDCDemo.java:51) - log in thread2 start
INFO [Thread-0] [77011a2b-d5ec-4846-8a0b-0177be25464c] (MDCDemo.java:46) - log in thread1 end
INFO [Thread-1] [ceace569-f862-41b6-97b6-0ed9561df5c3] (MDCDemo.java:57) - log in thread2 end

可以看到,thread1thread2各自的TRACE_ID互不影响