在application.properties中配置 logging.level.com.umgsai.core.dal=debug 可以在日志中打印出详细的SQL语句。
但是并不希望在线上环境也打印,此时需要在线上和线下配置不同的日志级别。
@Slf4j
@Service
public class DynamicLoggersConfig {
private static final String DAL_PACKAGE = "com.umgsai.core.dal";
@Value("${logging.level.com.umgsai.core.dal:info}")
private String dalLogLevel = "info";
@ApolloConfig
private Config config;
private final static String LoggerTag = "logging.level.";
private final LoggingSystem loggingSystem;
public DynamicLoggersConfig(LoggingSystem loggingSystem) {
Assert.notNull(loggingSystem, "LoggingSystem must not be null");
this.loggingSystem = loggingSystem;
}
@ApolloConfigChangeListener
private void configChangeListener(ConfigChangeEvent changeEvent) {
Set<String> keyNames = config.getPropertyNames();
for (String key : keyNames) {
if (StringUtils.containsIgnoreCase(key, LoggerTag)) {
String strLevel = config.getProperty(key, "info");
LogLevel level = LogLevel.valueOf(strLevel.toUpperCase());
loggingSystem.setLogLevel(key.replace(LoggerTag, ""), level);
}
log.info("{}:{}", key, config.getProperty(key, null));
}
}
@PostConstruct
private void setLogLevel() {
LogLevel level = LogLevel.valueOf(dalLogLevel.toUpperCase());
loggingSystem.setLogLevel(DAL_PACKAGE, level);
log.info("{}:{}", DAL_PACKAGE, dalLogLevel);
}
}