攜程 Apollo 配置中心 | 學習筆記(十三)| 如何將日誌配置檔案放入到Apollo配置中心並支援熱更新?
本章將介紹如何將日誌配置檔案放入到Apollo配置中心並支援熱更新
專欄目錄:
歡迎關注個人公眾號: Coder程式設計
歡迎關注個人網站:www.52melrin.com
需求
日誌模組是每個專案中必須的,用來記錄程式執行中的相關資訊。一般在開發環境下使用DEBUG級別的日誌輸出,為了方便檢視問題,而在線上一般都使用INFO或者ERROR級別的日誌,主要記錄業務操作或者錯誤的日誌。那麼問題來了,當線上環境出現問題希望輸出DEBUG日誌資訊輔助排查的時候怎麼辦呢?修改配置檔案,重新打包然後上傳重啟線上環境,之前確實是這麼做的。
接下來將介紹如何通過將日誌檔案部署到Apollo配置中心,並支援對日誌等級的修改達到熱更新。這裡日誌等級包括對單個類日誌檔案等級的支援、不同環境日誌等級的支援。
版本
Apollo: 0.10.2
SpringBoot: 2.0.3.RELEASE
單個類日誌檔案等級更改
場景:當我們發現定位到某個類中可能出現相關問題,需要進行問題排查時。可以單獨指定對單獨類,根據自己做的日誌記錄。進行日誌等級的更改並支援熱更新。
監聽日誌檔案變化
@Service public class LoggerConfiguration { private static final Logger logger = LoggerFactory.getLogger(LoggerConfiguration.class); private static final String LOGGER_TAG = "logging.level."; @Autowired private LoggingSystem loggingSystem; @ApolloConfig private Config config; @ApolloConfigChangeListener private void configChangeListter(ConfigChangeEvent changeEvent) { refreshLoggingLevels(); } @PostConstruct private void refreshLoggingLevels() { Set<String> keyNames = config.getPropertyNames(); for (String key : keyNames) { if (containsIgnoreCase(key, LOGGER_TAG)) { String strLevel = config.getProperty(key, "info"); LogLevel level = LogLevel.valueOf(strLevel.toUpperCase()); loggingSystem.setLogLevel(key.replace(LOGGER_TAG, ""), level); logger.info("{}:{}", key, strLevel); } } } private static boolean containsIgnoreCase(String str, String searchStr) { if (str == null || searchStr == null) { return false; } int len = searchStr.length(); int max = str.length() - len; for (int i = 0; i <= max; i++) { if (str.regionMatches(true, i, searchStr, 0, len)) { return true; } } return false; } }
測試類
@RestController public class LoggerTestController { private static Logger logger = LoggerFactory.getLogger(LoggerTestController.class); @RequestMapping(value = "/hello") public String hello() { logger.info("info--------------"); logger.error("error--------------"); logger.warn("warn--------------"); logger.debug("debug--------------"); return "Hello,World"; } }
場景驗證
當我們啟動完專案,發現定位到LoggerTestController這個類中的hello方法有問題。這時候我們需要調整日誌等級。
1.專案已經啟動好了,發現LoggerTestController有問題
可以看到專案已經啟動,部署完畢的狀態。
這裡,為了驗證先訪問:http://localhost:8099/hello 請求,控制檯輸出的是:
1.拷貝LoggerTestController全類路徑,在簽名加上logging.level.
這裡我的LoggerTestController全類路徑是:com.spring.boot.logger.controller.LoggerTestController
加上後的key : logging.level.com.spring.boot.logger.controller.LoggerTestController
把key部署到Apollo配置中心,value等級設定為warn
在不重啟服務的情況下,再次訪問http://localhost:8099/hello,控制檯輸出:
可以看到監聽事件,以及日誌等級的變成了warn等級。
繼續更改等級為error,可以看到日誌等級變成error等級了。這裡就不再放圖了。
不同環境日誌等級更改
場景:從上面場景可以看出是開發人員自己定義加入的日誌,下面的場景是對整個環境日誌等級的更改。例如:Spring環境日誌等級的更改
logging.level.org.springframework = debug
沿用上面的類檔案進行驗證
在不重啟專案的情況下,在Apollo配置中心中加入
Key =logging.level.org.springframework
Value= debug
再次訪問http://localhost:8099/hello,檢視控制檯輸出:
這時候可以看出日誌多了許多。
場景驗證結束,由此已經完成了將日誌配置檔案放入到Apollo配置中心並支援熱更新。