Java-如何配置log4j2.xml

时间:2019-07-18 11:53:53

标签: java spring-mvc log4j2

我想通过我的applicationContext.xml而不是web.xml配置log4j2.xml文件。如果类路径中存在此log4j2.xml文件,则无法对此文件进行任何更改。因此,我应该使用此applicationContext.xml进行配置。

pom.xml

<dependency> 
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.6.0</version>
    </dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.11.1</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.11.1</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-1.2-api</artifactId>
    <version>2.11.1</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-web</artifactId>
    <version>2.11.1</version>
</dependency>
<dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.2</version>
</dependency>

applicationContext.xml

<bean id="log4jInitialization" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="targetClass"
                  value="org.apache.logging.log4j.LogManager" />
        <property name="targetMethod" value="getContext" />
        <property name="arguments">
            <list>
                <value>false</value>
            </list>
        </property>
    </bean>

    <bean id="log4jContext" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="targetObject" ref="log4jInitialization"/>
        <property name="targetMethod" value="setConfigLocation"/>
        <property name="arguments">
            <list>
                <value>C:/projects/conf/log4j2.xml</value>
            </list>
        </property>
    </bean>

我认为LoggerContext类没有setConfigLocation()方法,因为getContext()返回log4j-api的LoggerContext类而不是log4j-core的

如何处理这种情况?谢谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我使用了如下所示的代码,并且在使用Tomcat Server时成功,但是如果使用WebSphere Server,则Program不会将日志打印到文件中。

<bean id="log4jInitialization" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="targetClass"
              value="org.apache.logging.log4j.core.LoggerContext" />
    <property name="targetMethod" value="getContext" />
    <property name="arguments">
        <list>
            <value>false</value>
        </list>
    </property>
</bean>

<bean id="log4jContext" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="targetObject" ref="log4jInitialization"/>
    <property name="targetMethod" value="setConfigLocation"/>
    <property name="arguments">
        <list>
            <!--<value>classpath:log4j2.xml</value>-->
            <value>file:c:/projects/conf/log4j2.xml</value>
        </list>
    </property>
</bean>