美文网首页
springcloud通过apollo动态配置logback

springcloud通过apollo动态配置logback

作者: 小诸葛686 | 来源:发表于2020-04-20 10:31 被阅读0次

    注:文中例子基于apollo官方提供的demo修改。
    1.application.properties配置

    app.id=spring-cloud-logger
    # set apollo meta server address, adjust to actual address if necessary
    apollo.meta=http://localhost:8080
    apollo.bootstrap.enabled=true
    apollo.bootstrap.namespaces=application
    apollo.bootstrap.eagerLoad.enabled=true
    logging.config=classpath:logback-test.xml
    

    通过apollo.bootstrap.eagerLoad.enabled=true来使Apollo的加载顺序放到日志系统加载之前,这样就能保证日志组件加载spring的配置。

    2.logback-test.xml配置

    <?xml version="1.0" encoding="UTF-8"?>
    
    <configuration>
        <springProperty scope="context" name="LOG_HOME" source="log.test.loghome" defaultValue="D:\\log\\"/>
    
        <!--控制台输出appender-->
        <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
            <!--设置输出格式-->
            <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
                <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
                <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
                <charset>UTF-8</charset>
            </encoder>
        </appender>
    
         <appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
                <file>${LOG_HOME}/test.log</file>
            <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                <FileNamePattern>${LOG_HOME}/test.log.%d{yyyy-MM-dd_HH}</FileNamePattern>
                <MaxHistory>10</MaxHistory>
            </rollingPolicy>
           <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
                    <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
                    <charset>UTF-8</charset>
                </encoder>
        </appender>
    
         <root level="DEBUG">
            <appender-ref ref="console"/>
            <appender-ref ref="file"/>
         </root>
    
    </configuration>
    

    3.开启apollo配置类

    package com;
    
    import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    
    @SpringBootApplication
    @EnableApolloConfig
    public class Application {
    
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    }
    

    4.配置动态生效核心类
    目前logback只能通过日志文件动态刷新,怎么通过apollo配置修改属性动态生效?
    目前通过apollo能动态生效的也只有日志级别。
    如果其他配置想通过apollo动态生效,如demo中的路径等配置,可以通过以下方式,当logback使用的spring变量发现修改后,可以重新初始化logback配置就能达到目标效果。

    例如:
    通过在apollo配置以下属性,可以让日志级别动态生效:

     logging.level.com.test = warn
    

    其他非日志级别属性,我们可以统一使用一个前缀地址,监听该前缀,当配置发现变化后,执行下面例子中的代码可以让logback动态生效。

    package com;
    
    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.springframework.beans.BeansException;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.logging.LoggingInitializationContext;
    import org.springframework.boot.logging.LoggingSystem;
    import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    import org.springframework.context.EnvironmentAware;
    import org.springframework.core.env.ConfigurableEnvironment;
    import org.springframework.core.env.Environment;
    import org.springframework.stereotype.Service;
    import org.springframework.util.ResourceUtils;
    
    import javax.annotation.PostConstruct;
    import java.util.Set;
    
    @Service
    public class LoggerLevelRefresher implements ApplicationContextAware, EnvironmentAware {
    
      private ApplicationContext applicationContext;
      private ConfigurableEnvironment environment;
    
      @Autowired
      private LoggingSystem loggingSystem;
    
      @ApolloConfig
      private Config config;
    
      @PostConstruct
      private void initialize() {
        refreshLoggingLevels(config.getPropertyNames());
      }
    
      @ApolloConfigChangeListener
      private void onChange(ConfigChangeEvent changeEvent) {
        refreshLoggingLevels(changeEvent.changedKeys());
      }
    
      @ApolloConfigChangeListener(interestedKeyPrefixes = {"log.test."})
      private void onChangeLog(ConfigChangeEvent changeEvent) {
        LoggingInitializationContext initializationContext = new LoggingInitializationContext(environment);
        String logConfig = environment.getProperty("logging.config");
        try{
          ResourceUtils.getURL(logConfig).openStream().close();
          loggingSystem.cleanUp();
          loggingSystem.initialize(initializationContext, logConfig, null);
        }catch (Exception e){
        }
      }
    
      private void refreshLoggingLevels(Set<String> changedKeys) {
        System.out.println("Refreshing logging levels");
    
        /**
         * refresh logging levels
         * @see org.springframework.cloud.logging.LoggingRebinder#onApplicationEvent
         */
        this.applicationContext.publishEvent(new EnvironmentChangeEvent(changedKeys));
    
        System.out.println("Logging levels refreshed");
      }
    
      @Override
      public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
      }
    
      @Override
      public void setEnvironment(Environment environment) {
        this.environment = (ConfigurableEnvironment) environment;
      }
    }
    

    5.github代码地址

    [https://github.com/495804928/logger](https://github.com/495804928/logger)
    
    

    相关文章

      网友评论

          本文标题:springcloud通过apollo动态配置logback

          本文链接:https://www.haomeiwen.com/subject/hkvlihtx.html