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

你可能感兴趣的:(springboot集成apollo动态刷新日志级别)