如何快速過濾出一次請求的所有日志?
閱讀本文大概需要 5 分鐘。
來自:wudashan.com/2018/02/15/Log-Request-In-MutiThread

華為IoT平臺,提供了接收設(shè)備上報數(shù)據(jù)的能力, 當(dāng)數(shù)據(jù)到達(dá)平臺后,平臺會進(jìn)行一些復(fù)雜的業(yè)務(wù)邏輯處理,如數(shù)據(jù)存儲,規(guī)則引擎,數(shù)據(jù)推送,命令下發(fā)等等。由于這個邏輯之間沒有強耦合的關(guān)系,所以通常是異步處理。如何將一次數(shù)據(jù)上報請求中包含的所有業(yè)務(wù)日志快速過濾出來,就是本文要介紹的。
02、正文
SLF4J日志框架提供了一個MDC(Mapped Diagnostic Contexts)工具類,谷歌翻譯為映射的診斷上下文 ,從字面上很難理解,我們可以先實戰(zhàn)一把。
public class Main {
private static final String KEY = "requestId";
private static final Logger logger = LoggerFactory.getLogger(Main.class);
public static void main(String[] args) {
// 入口傳入請求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");
// 出口移除請求ID
MDC.remove(KEY);
}
}
MDC.put()方法傳入請求ID,在出口調(diào)用MDC.remove()方法移除請求ID。配置好log4j2.xml 文件后,運行main函數(shù),可以在控制臺看到以下日志輸出:2018-02-17 13:19:52.606 {requestId=f97ea0fb-2a43-40f4-a3e8-711f776857d0} [main] DEBUG cn.wudashan.Main - log in main thread 1
2018-02-17 13:19:52.609 {requestId=f97ea0fb-2a43-40f4-a3e8-711f776857d0} [main] DEBUG cn.wudashan.Main - log in main thread 2
2018-02-17 13:19:52.609 {requestId=f97ea0fb-2a43-40f4-a3e8-711f776857d0} [main] DEBUG cn.wudashan.Main - log in main thread 3
put()和remove()代碼,在現(xiàn)網(wǎng)定位問題時,我們就可以通過grep requestId=xxx *.log快速的過濾出某次請求的所有日志。03、進(jìn)階
public class Main {
private static final String KEY = "requestId";
private static final Logger logger = LoggerFactory.getLogger(Main.class);
public static void main(String[] args) {
// 入口傳入請求ID
MDC.put(KEY, UUID.randomUUID().toString());
// 主線程打印<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>
new Thread(new Runnable() {
@Override
public void run() {
logger.debug("log in other thread");
}
}).start();
// 出口移除請求ID
MDC.remove(KEY);
}
}
2018-02-17 14:05:43.487 {requestId=e6099c85-72be-4986-8a28-de6bb2e52b01} [main] DEBUG cn.wudashan.Main - log in main thread
2018-02-17 14:05:43.490 {} [Thread-1] DEBUG cn.wudashan.Main - log in other thread
MDC.put()方法傳入的請求ID只在當(dāng)前線程有效。感興趣的小伙伴可以自己深入一下代碼細(xì)節(jié)。MDCRunnable類對Runnable接口進(jìn)行一層裝飾。在創(chuàng)建MDCRunnable類時保存當(dāng)前線程的MDC值,在執(zhí)行run()方法時再將保存的MDC值拷貝到異步線程中去。代碼實現(xiàn)如下:public class MDCRunnable implements Runnable {
private final Runnable runnable;
private final Map<String, String> map;
public MDCRunnable(Runnable runnable) {
this.runnable = runnable;
// 保存當(dāng)前線程的MDC值
this.map = MDC.getCopyOfContextMap();
}
@Override
public void run() {
// 傳入已保存的MDC值
for (Map.Entry<String, String> entry : map.entrySet()) {
MDC.put(entry.getKey(), entry.getValue());
}
// 裝飾器模式,執(zhí)行run方法
runnable.run();
// 移除已保存的MDC值
for (Map.Entry<String, String> entry : map.entrySet()) {
MDC.remove(entry.getKey());
}
}
}
public class Main {
private static final String KEY = "requestId";
private static final Logger logger = LoggerFactory.getLogger(Main.class);
private static final ExecutorService EXECUTOR = Executors.newSingleThreadExecutor();
public static void main(String[] args) {
// 入口傳入請求ID
MDC.put(KEY, UUID.randomUUID().toString());
// 主線程打印<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
public void run() {
logger.debug("log in other thread");
}
})).start();
// 異步線程池打印日志,用MDCRunnable裝飾Runnable
EXECUTOR.execute(new MDCRunnable(new Runnable() {
@Override
public void run() {
logger.debug("log in other thread pool");
}
}));
EXECUTOR.shutdown();
// 出口移除請求ID
MDC.remove(KEY);
}
}
2018-03-04 23:44:05.343 {requestId=5ee2a117-e090-41d8-977b-cef5dea09d34} [main] DEBUG cn.wudashan.Main - log in main thread
2018-03-04 23:44:05.346 {requestId=5ee2a117-e090-41d8-977b-cef5dea09d34} [Thread-1] DEBUG cn.wudashan.Main - log in other thread
2018-03-04 23:44:05.347 {requestId=5ee2a117-e090-41d8-977b-cef5dea09d34} [pool-2-thread-1] DEBUG cn.wudashan.Main - log in other thread pool
04、總結(jié)
推薦閱讀:
互聯(lián)網(wǎng)初中高級大廠面試題(9個G) 內(nèi)容包含Java基礎(chǔ)、JavaWeb、MySQL性能優(yōu)化、JVM、鎖、百萬并發(fā)、消息隊列、高性能緩存、反射、Spring全家桶原理、微服務(wù)、Zookeeper......等技術(shù)棧!
?戳閱讀原文領(lǐng)??! 朕已閱


