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

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

  • 添加次配置后,当在apollo上面调整日志级别不需要重启服务器,马上就能生效

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    /**
    * 结合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;
    }
    }