问题
I am using spring mvc 3. Today I discovered spring profiles and how you can set them in your web.xml. I am loading my profile from an application properties file but cannot achieve the same thing with log4j in order to load a different log4j file based on whether or not I am building for dev or building for prod.
Here is what I have for spring.profiles.active.
A properties file named env.properties..
spring.profiles.active=dev
An AppInitializer class which implements ApplicationContextInitializer.
public void initialize(ConfigurableApplicationContext applicationContext) { ConfigurableEnvironment environment = applicationContext.getEnvironment(); try { ResourcePropertySource env = new ResourcePropertySource("classpath:env.properties"); String profile = (String)env.getProperty("spring.profiles.active"); environment.getPropertySources().addFirst(env); ... }The following in my web.xml
<context-param> <param-name>spring.profiles.active</param-name> <param-value>${spring.profiles.active}</param-value> </context-param>
Problem : Now I try and load a different log file based on env like so...
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:/log4j-${spring.profiles.active}.xml</param-value>
</context-param>
Where the aim is to load log4j-dev.xml but this does not work.
Can anyone help me with this please?
thanks
回答1:
Log4j supports variable substitution inside the log4j.xml file. You could substitute the log directory based on an environment specific system property. That would mean that you could keep the file name as:
<param-value>classpath:/log4j.xml</param-value>
Then you could parameterize the directory inside the file:
<param name="File" value="${log4j_dir}/filename.log" />
And then for each app server in each environment, you could set the appropriate folder path. Eg. for dev:
-Dlog4j_dir=/path/on/dev
It does mean that you'd be using a system property rather than a property in a properties file but it may be one way of achieving what you're after.
来源:https://stackoverflow.com/questions/21544718/spring-mvc-loading-different-log4j-file-per-build-environment