Apollo配置中心动态刷新日志级别

时间:2024-04-04 23:04:04

Apollo配置中心动态刷新日志级别

  • 添加次配置后,当在apollo上面调整日志级别不需要重启服务器,马上就能生效
/**
* 结合apollo动态刷新日志级别
* @author: nj
* @date: 2019/1/21:下午5:00
*/
@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;
}
}