apollo配置logback日志级别

apollo配置logback日志级别
强烈推介IDEA2021.1.3破解激活,IntelliJ IDEA 注册码,2021.1.3IDEA 激活码  

大家好,我是架构君,一个会写代码吟诗的架构师。今天说一说apollo配置logback日志级别,希望能够帮助大家进步!!!

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

 

本文来源huayang183,由架构君转载发布,观点不代表Java架构师必看的立场,转载请标明来源出处:https://javajgs.com/archives/17983

发表评论