當前位置: 妍妍網 > 碼農

SpringBoot 如何快速過濾出一次請求的所有日誌?

2024-03-19碼農

來源: wudashan.com/2018/02/15/Log-Request-In-MutiThread

在現 網出 現故障時,我們經常需要獲取一次請求流程裏的所有日誌進行 定位 。如果請求只在一個執行緒裏處理,則我們可以透過執行緒ID來 過濾 日誌 ,但如果請求包含異步執行緒的處理,那麽光靠執行緒ID就顯得捉襟見肘了。

華為IoT平台,提供了接收裝置上報數據的能力, 當數據到達平台後,平台會進行一些復雜的業務邏輯處理,如數據儲存,規則引擎,數據推播,命令下發等等。由於這個邏輯之間沒有強耦合的關系,所以通常是異步處理。如何將一次數據上報請求中包含的所有業務日誌快速過濾出來,就是本文要介紹的。

正文

SLF4J日誌框架提供了一個MDC(Mapped Diagnostic Contexts)工具類,谷歌轉譯為 對映的診斷上下文 ,從字面上很難理解,我們可以先實戰一把。

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);
}
}



我們在main函式的入口呼叫 MDC.put() 方法傳入請求ID,在出口呼叫 MDC.remove() 方法移除請求ID。配置好 log4j2.xml 檔後,執行main函式,可以在控制台看到以下日誌輸出:

2018-02-17 13:19:52.606 {requestId=f97ea0fb-2a43-40f4-a3e8-711f776857d0} [main] DEBUG cn.wudashan.Main - login main thread 1
2018-02-17 13:19:52.609 {requestId=f97ea0fb-2a43-40f4-a3e8-711f776857d0} [main] DEBUG cn.wudashan.Main - login main thread 2
2018-02-17 13:19:52.609 {requestId=f97ea0fb-2a43-40f4-a3e8-711f776857d0} [main] DEBUG cn.wudashan.Main - login main thread 3

從日誌中可以明顯地看到花括弧中包含了 (對映的) 請求ID(requestId),這其實就是我們定位 (診斷) 問題的關鍵字 (上下文) 。有了MDC工具,只要在介面或切面植入 put() remove() 程式碼,在現網定位問題時,我們就可以透過 grep requestId=xxx *.log 快速的過濾出某次請求的所有日誌。

進階

然而,MDC工具真的有我們所想的這麽方便嗎?回到我們開頭,一次請求可能涉及多執行緒異步處理,那麽在多執行緒異步的場景下,它是否還能正常運作呢?Talk is cheap, show me the code。

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 >"color: #1e6bb8;word-wrap: break-word;font-weight: bold;border-bottom: 1px solid">日誌</font>
logger.debug("log in main thread");
// 異步執行緒打印<font >"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);
}
}






程式碼裏我們新起了一個異步執行緒,並在匿名物件Runnable的run()方法打印日誌。執行main函式,可以在控制台看到以下日誌輸出:

2018-02-17 14:05:43.487 {requestId=e6099c85-72be-4986-8a28-de6bb2e52b01} [main] DEBUG cn.wudashan.Main - login main thread
2018-02-17 14:05:43.490 {} [Thread-1] DEBUG cn.wudashan.Main - login other thread

不幸的是,請求ID在異步執行緒裏不打印了。這是怎麽回事呢?要解決這個問題,我們就得知道MDC的實作原理。由於篇幅有限,這裏就暫不詳細介紹,MDC之所以在異步執行緒中不生效是因為底層采用 ThreadLocal 作為數據結構,我們呼叫 MDC.put() 方法傳入的請求ID只在當前執行緒有效。感興趣的小夥伴可以自己深入一下程式碼細節。

知道了原理那麽解決這個問題就輕而易舉了,我們可以使用 裝飾器模式 ,新寫一個 MDCRunnable類 Runnable介面 進行一層裝飾。在建立 MDCRunnable類 時保存當前執行緒的MDC值,在執行 run() 方法時再將保存的MDC值拷貝到異步執行緒中去。程式碼實作如下:

public class MDCRunnable implements Runnable {
private final Runnable runnable;
private final Map<String, String> map;
public MDCRunnable(Runnable runnable) {
this.runnable = runnable;
// 保存當前執行緒的MDC值
this.map = MDC.getCopyOfContextMap();
}
@Override
public void run() {
// 傳入已保存的MDC值
for (Map.Entry<String, String> entry : map.entrySet()) {
MDC.put(entry.getKey(), entry.getValue());
}
// 裝飾器模式,執行run方法
runnable.run();
// 移除已保存的MDC值
for (Map.Entry<String, String> entry : map.entrySet()) {
MDC.remove(entry.getKey());
}
}
}



接著,我們需要對main函式裏建立的Runnable實作類進行裝飾:

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 >"color: #1e6bb8;word-wrap: break-word;font-weight: bold;border-bottom: 1px solid">日誌</font>
logger.debug("log in main thread");
// 異步執行緒打印<font >"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);
}
}







執行main函式,將會輸出以下 日誌

2018-03-04 23:44:05.343 {requestId=5ee2a117-e090-41d8-977b-cef5dea09d34} [main] DEBUG cn.wudashan.Main - login main thread
2018-03-04 23:44:05.346 {requestId=5ee2a117-e090-41d8-977b-cef5dea09d34} [Thread-1] DEBUG cn.wudashan.Main - login other thread
2018-03-04 23:44:05.347 {requestId=5ee2a117-e090-41d8-977b-cef5dea09d34} [pool-2-thread-1] DEBUG cn.wudashan.Main - login other thread pool

Congratulations! 經過我們的努力,最終在異步執行緒和執行緒池中都有requestId打印了!

總結

本文講述了如何使用MDC工具來快速過濾一次請求的所有 日誌 ,並透過裝飾器模式使得MDC工具在異步執行緒裏也能生效。有了MDC,再透過AOP技術對所有的切面植入requestId,就可以將整個系統的任意流程的日誌過濾出來。使用MDC工具,在開發自測階段,可以極大地節省定位問題的時間,提升開發效率;在運維維護階段,可以快速地收集相關日誌資訊,加快分析速度。

>>

END

精品資料,超贊福利,免費領

微信掃碼/長按辨識 添加【技術交流群

群內每天分享精品學習資料

最近開發整理了一個用於速刷面試題的小程式;其中收錄了上千道常見面試題及答案(包含基礎並行JVMMySQLRedisSpringSpringMVCSpringBootSpringCloud訊息佇列等多個型別),歡迎您的使用。

👇👇

👇點選"閱讀原文",獲取更多資料(持續更新中