Freemarker, slf4j and spring

I’ve just spent three hours trying to get Freemarker to stop spitting out “DEBUG cache:81” messages in my Spring application.

Freemarker recently hacked in SLF4J support into 2.3, but I had a hard time finding out how to enable it, so I reckoned I’d share my experiences.

FreeMarker 2.3 looks for logging libraries in this order (by default) with the class-loader of the FreeMarker classes: Log4J, Avalon, java.util.logging. The first that it founds in this list will be the one used for logging.

I found out that you can override this behavior in 2.3.18 by calling:

freemarker.log.Logger.
    selectLoggerLibrary(freemarker.log.Logger.LIBRARY_SLF4J);

However, this code need to run before any Freemarker classes are initialized.

After trying a few different tricks, such as having a load-on-startup Servlet’s init() configure the logger, I ended up with a fairly clean solution.

I extended Spring’s FreeMarkerConfigurer class like this:

 public class PluxFreeMarkerConfigurer extends FreeMarkerConfigurer {
    private Logger logger = LoggerFactory
            .getLogger(PluxFreeMarkerConfigurer.class);

    @Override
    public void afterPropertiesSet() throws IOException, TemplateException {
        fixFreemarkerLogging();
        super.afterPropertiesSet();
    }

    private void fixFreemarkerLogging() {
        try {
            freemarker.log.Logger
              .selectLoggerLibrary(freemarker.log.Logger.LIBRARY_SLF4J);
            logger.info("Switched broken Freemarker logging to slf4j");
        } catch (ClassNotFoundException e) {
            logger.warn("Failed to switch broken Freemarker logging to slf4j");
        }
    }
}

and changed my Spring-config to use my class to initialize Freemarker instead:

  <!-- FreeMarker engine that configures Freemarker for SLF4J-->
  <bean id="freemarkerConfig" class="com.selessia.plux.web.PluxFreeMarkerConfigurer"
 ...
 </bean>

Hope this helps someone.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s