apollo配置logback日誌級別
阿新 • • 發佈:2021-01-20
- Apollo配置
apollo.bootstrap.enabled=true
#開啟後,Apollo的配置會先於logback的配置載入
apollo.bootstrap.eagerLoad.enabled=true
- apollo增加日誌等級配置項(日誌等級(級別由大到小): OFF、ERROR、WARN、INFO、DEBUG)
loggers.root.root=INFO
- 增加日誌等級修改監聽配置類(LogListenerConfig)
package com.github.pig.common.bean.config; import com.ctrip.framework.apollo.Config; import com.ctrip.framework.apollo.model.ConfigChangeEvent; import com.ctrip.framework.apollo.spring.annotation.ApolloConfig; import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.logging.LogLevel; import org.springframework.boot.logging.LoggerConfiguration; import org.springframework.boot.logging.LoggingSystem; import org.springframework.context.annotation.Configuration; import javax.annotation.PostConstruct; import java.util.Set; /** * 結合apollo動態重新整理日誌級別 */ @Configuration public class LogListenerConfig { private static final Logger logger = LoggerFactory.getLogger(LoggerConfiguration.class); /** * 監聽關鍵字,當配置中心的依次開頭的配置發生變化時,日誌級別重新整理 */ private static final String LOGGER_TAG = "loggers.root."; @Autowired private LoggingSystem loggingSystem; /** * 可以指定具體的namespace,未指定時使用的是 application這個namespace */ @ApolloConfig private Config config; @ApolloConfigChangeListener private void onChange(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); loggingSystem.setLogLevel("", 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; } }