简体   繁体   中英

How to get a dynamic value from .properties file for log4j.xml

I am using log4j.xml file. I have two environments namely live & test. The only difference in the log4j for the test and live are the levels (INFO-live, DEBUG-test). So i have kept the common log4j.xml for both env and made the level as value=${loglevel}. I have defined separate live-log4j.properties which contains loglevel=INFO . likewise for test as well. My idea is, if i build the jar for live, the loglevel should be picked from the live-log4j.properties file. If for test build, then from test-log4j.properties.

Here my query is, am i doing the right thing? will the log4j.xml will pick the values from the respective *.properties file?

I am using spring framework. I have referred lot of stuffs, but nothing is relevant to this. I have added these properties files in the spring.xml (not sure if it work) I don't have client connectivity to test this app.

My log4j version: log4j 1.x

Here is a post that explain how to: log4j configuration in applicationContext - forum.spring.io

you can simplify that

ApplicationContext.xml:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>test-log4j.properties</value>
            <value>live-log4j.properties</value>
        </list>
    </property>
</bean>

<bean id="log4jDirectConfigurer" class="my.commons.logging.Log4jDirectConfigurer">
    <property name="location" value="classpath:log4j.xml"/>
    <property name="loglevelValue" value="${logging.level}"/>
</bean>

Log4jDirectConfigurer.java:

package my.commons.logging;

import java.io.FileNotFoundException;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Log4jConfigurer;

public class Log4jDirectConfigurer implements InitializingBean 
{
    private String location;
    private String loglevelKey = "webapp.logLevel";

    public void setLocation( String location ){
        this.location = location;
    }

    public void setLoglevelValue( String loglevel ){
        String value = System.getProperty( loglevelKey );
        System.setProperty( loglevelKey, loglevel );
    }

    public void afterPropertiesSet() {
        if( location == null ){
            return;
        }

        try {
            Log4jConfigurer.initLogging( location );
        } catch (FileNotFoundException e) {
            System.out.println(location + ": File not found");
        }
    }
}

log4j.xml:

<root>
    <level value="${webapp.logLevel}" />
</root>

live-log4j.properties:

logging.level=INFO

test-log4j.propertie:

logging.level=DEBUG

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM