Using LogbackConfigurer

The LogbackConfigurer is  bean to help you configure Logback manually in Spring applications.  You can:

  • pass one or more logback xml files where the latter will extend the configuration created by the former
    • this way you can easily use a global logback.xml file and extend it for different environments
  • use a default log directory that is passed as a ${log.dir} property to the xml files

By default Logback will go looking for a logback.xml file in the resource root.  It will use that one if it is available in which case you do not need separate configuration.  You can combine the default behavior with a LogbackConfigurer bean as the latter will replace the default configuration once it is initialized.

Availability

LogbackConfigurer is available in the common-spring library.  It requires Logback to be present on the classpath, the logback dependency will not be added transitively by including common-spring.

Examples

Example using @Configuration classes:

@Bean
public LogbackConfigurer logbackConfigurer( @Value("${log.dir}") String logDir,
                                            @Value("${log.config}") Resource baseConfig,
                                            @Value("${log.config.extend}") Resource envConfig ) {
	return new LogbackConfigurer( logDir, baseConfig, envConfig );
} 

Example using XML:

<bean class="com.foreach.spring.logging.LogbackConfigurer" lazy-init="false">
	<constructor-arg name="logDir" value="${log.dir}"/>
	<constructor-arg name="configurationResources">
		<set>
			<value>classpath:/config/logback.xml</value>
		</set>
	</constructor-arg>
</bean>

Sample properties file:

# logging configuration
log.dir=/logs/imageserver
log.config=classpath:/config/logback.xml
log.config.extend=classpath:/config/development/logback.xml 

You can pass any number of resources and it is not required that they exists.  Logging configuration happens in the configure() method, called as a @PostConstruct on the bean.  If you are not using Spring beans you have to call the method manually.

Extensions

There is a LogbackConfigurerAdapter class available that allows you to extend the default behaviour.