in how to java spring log4j enviroments ~ read.

Environment specific logging based on log4j

I suppose every big project at last face with logging problems, cause during product lifecycle it should pass throught some environments (development, test, production). Ideally each environment should have its own logging setting.

I also faced with this problem, when come to new project this year. The project was started some years ago and currently this is a big enterprise legacy project with Spring IoC with a lot old libs, where updating lib version cause a lot of QA, so libs versions increments very slow. So we have new feature in new versions out of the boat, while pursuit for stability. The same is for logging - it was based on log4j 1.2 with one config file for all enviroments.

And what we are looking: one log config per environment, which will be load automaticly where run on some environment. Here I should notice that our app already recive variable with name of environment as Java -Denvironment parameter, so I will use it in logging problems.

Such selection of configs could be perfomed automaticly, during Spring context loading. All you need is add such bean definition:

<bean id="log4jConfigurer" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="targetClass" value="org.springframework.util.Log4jConfigurer"/>
<property name="targetMethod" value="initLogging"/>
<property name="arguments"> <list> <value>classpath:config/log4j.${environment}.xml</value> </list> </property> </bean>

Here we just call Log4jConfigurer.initLogging() method from Spring lib and pass as parameter path to enviroment specific config. As you can see path contains place holder ${environment}, which will replaced with value of 'environment' variable passed to JVM on start. So depending on name of environment, we will use specific config file to init log4j. All we need to do is in folder 'config' of classpath place config file for every enviroment we have with names like log4j.MyEnvironment.xml.

comments powered by Disqus