// 入口传入请求ID MDC.put(KEY, UUID.randomUUID().toString()); // 打印日志 logger.debug("log in main thread 1"); logger.debug("log in main thread 2"); logger.debug("log in main thread 3");
2018-02-1714:05:43.487 {requestId=e6099c85-72be-4986-8a28-de6bb2e52b01} [main] DEBUG cn.wudashan.Main - log in main thread 2018-02-1714:05:43.490 {} [Thread-1] DEBUG cn.wudashan.Main - log in other thread
// 主线程打印<font style="color: #1e6bb8;word-wrap: break-word;font-weight: bold;border-bottom: 1px solid">日志</font> logger.debug("log in main thread");
// 异步线程打印<font style="color: #1e6bb8;word-wrap: break-word;font-weight: bold;border-bottom: 1px solid">日志</font>,用MDCRunnable装饰Runnable new Thread(new MDCRunnable(new Runnable() { @Override publicvoidrun(){ logger.debug("log in other thread"); } })).start();
// 异步线程池打印日志,用MDCRunnable装饰Runnable EXECUTOR.execute(new MDCRunnable(new Runnable() { @Override publicvoidrun(){ logger.debug("log in other thread pool"); } })); EXECUTOR.shutdown();
// 出口移除请求ID MDC.remove(KEY);
}
}
执行main函数,将会输出以下日志:
1 2 3
2018-03-0423:44:05.343 {requestId=5ee2a117-e090-41d8-977b-cef5dea09d34} [main] DEBUG cn.wudashan.Main - log in main thread 2018-03-0423:44:05.346 {requestId=5ee2a117-e090-41d8-977b-cef5dea09d34} [Thread-1] DEBUG cn.wudashan.Main - log in other thread 2018-03-0423:44:05.347 {requestId=5ee2a117-e090-41d8-977b-cef5dea09d34} [pool-2-thread-1] DEBUG cn.wudashan.Main - log in other thread pool