jueves, febrero 12, 2015

Grails in prod with an external log4j properties

Maybe you have tried to config your Grails app so you can:


  • Use the default logging configuration inside Config.groovy for test or dev.
  • Use an external log4j.properties file in production.


It's quite frustating and it is not so well documented.
After some digging I came up with a quite elegant solution:

Config.groovy:
----------------------------

import grails.util.Environment

if(Environment.current!=Environment.PRODUCTION){
  // log4j configuration
  log4j = {
    ...
  }
}


resources.groovy:
----------------------------

import grails.util.Environment

if(Environment.current==Environment.PRODUCTION){
  log4jConfigurer(org.springframework.beans.factory.config.MethodInvokingFactoryBean) {
    targetClass = "org.springframework.util.Log4jConfigurer"
    targetMethod = "initLogging"
    arguments = ["classpath:resources/log4j.properties"]
  }
} 


log4j.properties (src/resources/log4j.properties):
----------------------------
  //whatever make sense to you

Please remember NOT to forget your imports or otherwise it wont work.

Hope it helps!

PD: Grails 3.0 is about to see the light and ...well who kows!. This solution is right for Grails 2.x family.