简体   繁体   中英

Spring boot - logging to file using @PropertySource not working

I have a spring boot library module and I want to enable logging into a file. What I did was to add logging settings in module-conf.properties, but no file is created.

module-conf.properties

logging.file.name=test.log

I also created a configuration bean:

@Configuration
@ComponentScan("...")
@EnableJpaRepositories("...")
@PropertySource("classpath:module-conf.properties")

public class ModuleConfiguration {

    @Autowired
    private Environment environment;

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("org.postgresql.Driver");
        dataSource.setUrl(environment.getProperty("spring.datasource.url"));
        dataSource.setUsername(environment.getProperty("spring.datasource.username"));
        dataSource.setPassword(environment.getProperty("spring.datasource.password"));
        return dataSource;
    }

Do I have to configure the logging system the same way I configure the datasource?

Is there a way avoid manual configuration?

This is interesting!

It appears logging is initialized before the ApplicationContext is created.... and the @PropertySources is read after ApplicationContext is created. As per the documentation, you can override the config by updating one of the config file based on your logging system (Spring's default is logback)

Reference: https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-custom-log-configuration

Problem:

Since logging is initialized before the ApplicationContext is created, it is not possible to control logging from @PropertySources in Spring @Configuration files. The only way to change the logging system or disable it entirely is via System properties.

The recommendation:

When possible, we recommend that you use the -spring variants for your logging configuration (for example, logback-spring.xml rather than logback.xml). If you use standard configuration locations, Spring cannot completely control log initialization.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM