How to log the active configuration in a Spring Boot application?

前端 未结 5 1516
野性不改
野性不改 2020-12-14 15:51

I would really like to use YAML config for Spring Boot, as I find it quite readable and useful to have a single file showing what properties are active in my different profi

5条回答
  •  温柔的废话
    2020-12-14 16:54

    Actuator /env service displays properties, but it doesn't displays which property value is actually active. Very often you may want to override your application properties with

    • profile-specific application properties
    • command line arguments
    • OS environment variables

    Thus you will have the same property and different values in several sources.

    Snippet bellow prints active application properties values on startup:

    @Configuration
    public class PropertiesLogger {
        private static final Logger log = LoggerFactory.getLogger(PropertiesLogger.class);
    
        @Autowired
        private AbstractEnvironment environment;
    
        @PostConstruct
        public void printProperties() {
    
            log.info("**** APPLICATION PROPERTIES SOURCES ****");
    
            Set properties = new TreeSet<>();
            for (PropertiesPropertySource p : findPropertiesPropertySources()) {
                log.info(p.toString());
                properties.addAll(Arrays.asList(p.getPropertyNames()));
            }
    
            log.info("**** APPLICATION PROPERTIES VALUES ****");
            print(properties);
    
        }
    
        private List findPropertiesPropertySources() {
            List propertiesPropertySources = new LinkedList<>();
            for (PropertySource propertySource : environment.getPropertySources()) {
                if (propertySource instanceof PropertiesPropertySource) {
                    propertiesPropertySources.add((PropertiesPropertySource) propertySource);
                }
            }
            return propertiesPropertySources;
        }
    
        private void print(Set properties) {
            for (String propertyName : properties) {
                log.info("{}={}", propertyName, environment.getProperty(propertyName));
            }
        }
    
    }
    

提交回复
热议问题