zoukankan      html  css  js  c++  java
  • springboot集成apollo动态刷新日志级别

    还是老规矩,直接上代码

    @Configuration
    public class LogListenerConfig {
        private static final Logger log = LoggerFactory.getLogger(LoggerConfiguration.class);
        private static final String PREFIX = "logging.all.";
        private static final String ROOT = LoggingSystem.ROOT_LOGGER_NAME;
    
        @Resource
        private LoggingSystem loggingSystem;
    
        @ApolloConfigChangeListener("LogNameSpace")//这里填日志配置的命名空间
        private void onChange(ConfigChangeEvent changeEvent) {
            refreshLoggingLevels(changeEvent);
        }
    
        private void refreshLoggingLevels(ConfigChangeEvent changeEvent) {
            for (String key : changeEvent.changedKeys()) {
                // key may be : logging.all.level
                if (StringUtils.startsWithIgnoreCase(key, PREFIX)) {
                    log.error("changed value {} ", changeEvent.getChange(key));
                    String loggerName = ROOT;
                    String strLevel = changeEvent.getChange(key).getNewValue();
                    LogLevel level = LogLevel.valueOf(strLevel.toUpperCase());
                    loggingSystem.setLogLevel(loggerName, level);
    
                    log(loggerName, strLevel);
                }
            }
        }
    
        /**
         * 获取当前类的Logger对象有效日志级别对应的方法,进行日志输出。举例:
         * 如果当前类的EffectiveLevel为WARN,则获取的Method为 `org.slf4j.Logger#warn(java.lang.String, java.lang.Object, java.lang.Object)`
         * 目的是为了输出`changed {} log level to:{}`这一行日志
         */
        private void log(String loggerName, String strLevel) {
            try {
                LoggerConfiguration loggerConfiguration = loggingSystem.getLoggerConfiguration(log.getName());
                Method method = log.getClass().getMethod(loggerConfiguration.getEffectiveLevel().name().toLowerCase(), String.class, Object.class, Object.class);
                method.invoke(log, "changed {} log level to:{}", loggerName, strLevel);
            } catch (Exception e) {
                log.error("changed {} log level to:{} error", loggerName, strLevel, e);
            }
        }
    }
    

    完啦,so easy

  • 相关阅读:
    firefox上网问题解决
    ubuntu内核的编译安装
    ubuntu常用命令
    source insight 添加文件类型
    ubuntu版本查看命令
    百年孤独与拉丁美洲历史--转载
    Guess Number Higher or Lower II--困惑
    Symmetric Tree
    一棵开花的树
    yii2 mysql数据库读写分离配置
  • 原文地址:https://www.cnblogs.com/aohongzhu/p/12938730.html
Copyright © 2011-2022 走看看