How to use an external log4j.properties in you Grails project

| Comments

In a recent Grails project, I had to follow some corporate guidelines regarding application deployment, and one of those were that the log4j configuration for an application must be externalized in a properties file.

I searched for a Grails plugin that could help me with this, with no luck. Then I remembered that a Grails application is just a Spring application in disguise, so I looked for a Spring way to do this.

There are at least two ways to do this using Spring: Log4jConfigListener and Log4jConfigurer. I chose the later because the former assumes an expanded WAR file, which was not my case.

Here’s the recipe I came up with:

  • Configure a Log4jConfigurer Spring bean in your grails-app/conf/resources.groovy: (click here for a xml version)
beans = {
    log4jConfigurer(org.springframework.beans.factory.config.MethodInvokingFactoryBean) {
        targetClass = "org.springframework.util.Log4jConfigurer"
        targetMethod = "initLogging"
        arguments = ["classpath:myapp/log4j.properties"]
    }

    ...

}
  • Install the templates in your project with grails install-templates, so you can change some files used for Grails’ code generation. The one we are interested in is the web.xml template.

  • Comment out the Grails’ Log4jConfigListener from the src/templates/war/web.xml template:

    <filter-mapping>
        <filter-name>sitemesh</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>


    <!-- Comment this out!
    <listener>
        <listener-class>org.codehaus.groovy.grails.web.util.Log4jConfigListener</listener-class>
    </listener>
    -->

    <listener>
        <listener-class>org.codehaus.groovy.grails.web.context.GrailsContextLoaderListener</listener-class>
    </listener>
  • You can (and should) remove the log4j configuration block from your Config.groovy

  • That’s it!

This was tested with Grails 1.3.3, deploying to an Oracle WebLogic 10.3.0 container.

Comments